def viz_delay_on_map(map, df_station_geo_delay_hour, hour): df_station_geo_delay_hour = df_station_geo_delay_hour[[ 'lat', 'len', 'difference colour', 'Naam van de halte' ]] for index, row in dataframe_lat_len.iterrows(): folium.CircleMarker(location=[row[0], row[1]], fill=True, radius=2, color=row[2], popup=row[3]).add_to(map) legend = ''' <div style="position: fixed; bottom: 65px; left: 50px; width: 100px; height: 180px; border:2px solid grey; z-index:9999; font-size:14px; "> Delay (min) <br> >120 <i class="fa fa-circle" style="color:#ff0000"></i><br> >90   <i class="fa fa-circle" style="color:#ff4000"></i><br> >60   <i class="fa fa-circle" style="color:#ff8000"></i><br> >30   <i class="fa fa-circle" style="color:#ffbf00"></i><br> >15   <i class="fa fa-circle" style="color:#ffff00"></i><br> >5     <i class="fa fa-circle" style="color:#80ff00"></i><br> <5     <i class="fa fa-circle" style="color:#40ff00"></i><br> </div> ''' time = ''' <div style="position: fixed; top: 100px; left: 75px; width: 100px; height: 15px; z-index:9999; font-size:25px; ">''' + hour + ''' </div> ''' map.get_root().html.add_child(folium.Element(legend)) map.get_root().html.add_child(folium.Element(time)) return map
def generate_map_report(ip_address, response): """[a function that gets IP address and IP address information to apply them in a map and a table with IP information] Args: ip_address ([string]): [variable that crack ip address in a map] response ([dictionary]): [used to apply IP information assigned in response in a table] """ global HTML_TABLE_CODE REPORT_TITLE = f"{ip_address}-Report.html" os.chdir(os.path.dirname(__file__)) country = response['country']['names']['en'] continent = response['continent']['names']['en'] city = response['city']['names']['en'] latitude = response['location']['latitude'] accuracy_radius = response['location']['accuracy_radius'] longitude = response['location']['longitude'] time_zone = response['location']['time_zone'] state = response['subdivisions'][0]['names']['en'] # ip_address, country, continent, city, latitude, longitude, accuracy_radius, time_zone, state HTML_TABLE_CODE = HTML_TABLE_CODE.format(ip_address, country, continent, city, latitude, longitude, accuracy_radius, time_zone, state) geolocation = geocoder.ip(ip_address) ip_geolocation = geolocation.latlng my_map = folium.Map(location=ip_geolocation, zoom_start=15) # making circle folium.CircleMarker(location=ip_geolocation, radius=55).add_to(my_map) folium.Marker(ip_geolocation, popup=city).add_to(my_map) my_map.get_root().html.add_child(folium.Element(CSS_CODE)) my_map.get_root().html.add_child(folium.Element(HTML_TABLE_CODE)) my_map.save(REPORT_TITLE)
def createHtml(map, dest_filename = 'map.html'): title_html = """<h3>COVID19 összesített esetszám településenként (2020.03.04-2021.02.14.-ig) </h3> Az adatok forrása: https://docs.google.com/spreadsheets/d/1ConGRVdv8jocW8G1lhpLqbDVnYwibjP1xhQJ5qiP_Ew/edit#gid=1499258253 <br>""" map.get_root().html.add_child(fl.Element(title_html)) map.save(dest_filename)
def nearMe(): API_KEY = 'AIzaSyCJM2_o-SpAVPLrLXKL2-6JNeQRTbdUuno' google_places = GooglePlaces(API_KEY) my_location = geocoder.ip('me') lat, lng = my_location.latlng query_result = google_places.nearby_search( lat_lng ={'lat': lat, 'lng': lng}, radius = 5000, types =[types.TYPE_HOSPITAL]) name = [] coord = [] coords_1 = (lat, lng) # Iterate over the search results for place in query_result.places: coords_2 = ( float(place.geo_location['lat']), float(place.geo_location['lng'])) coord.append([ float(place.geo_location['lat']), float(place.geo_location['lng']) ]) x = round(geopy.distance.distance(coords_1, coords_2).km, 5) if x >= 1: dis = " Distance: " + str(x) + "km" else: dis = " Distance: " + str(round(x*1000, 2)) + "m" name.append(place.name + dis) df_text = name locations = coord map2 = folium.Map(location=my_location.latlng, tiles='CartoDB dark_matter', zoom_start=12) marker_cluster = MarkerCluster().add_to(map2) title_html = ''' <h3 align="center" style="font-size:20px"><b>Hospitals And Medical Stores Near You</b></h3> ''' map2.get_root().html.add_child(folium.Element(title_html)) folium.Marker( location=my_location.latlng, popup='Your Location', icon=folium.Icon(color='darkblue', icon_color='white', icon='male', angle=0, prefix='fa') ).add_to(map2) folium.Circle( location=[lat, lng], radius=5000, color='#3186cc', fill=True, fill_color='#3186cc' ).add_to(map2) for point in range(0, len(locations)): folium.Marker(locations[point], popup = folium.Popup(df_text[point]), ).add_to(marker_cluster) map2.save('templates/nearMe.html') return render_template('nearMe2.html')
def delta3(LAT, LON): loc = 'There is a high chance of flood' title_html = '''<h3 align="center" style="font-size:26px"><b>{}</b></h3>'''.format( loc) o = folium.Map(location=[LAT, LON], zoom_start=11, zoom_control=False, scrollWheelZoom=False, dragging=False) folium.Circle( radius=1000, location=[LAT, LON], color='crimson', fill=False, ).add_to(o) folium.Circle( radius=5000, location=[LAT, LON], color='crimson', fill=False, ).add_to(o) folium.Circle( radius=3000, location=[LAT, LON], color='crimson', fill=False, ).add_to(o) o.get_root().html.add_child(folium.Element(title_html)) o.save('templates/map-with-title.html')
def _add_heatmap(self, map_obj, points, intensity=None, max_intensity=None): ''' Creates a heatmap over a map depending on the density of the points given. ''' if intensity is None: points_to_plot = list(zip([x[0] for x in points], [x[1] for x in points], [1]*len(points))) max_intensity=1 else: points_to_plot = list(zip([x[0] for x in points], [x[1] for x in points], intensity)) if max_intensity is None: max_intensity = max(intensity) folium.plugins.HeatMap( points_to_plot, min_opacity=0.3, max_val=max_intensity, gradient=self.gradient, radius=37, blur=70 ).add_to(map_obj) # hacky way of changing heatmap opacity style_statement = '<style>.leaflet-heatmap-layer{opacity: ' + self.heatmap_opacity + '}</style>' map_obj.get_root().html.add_child(folium.Element(style_statement)) return map_obj
def map(): dataset = pd.read_csv('/Mini/lab_coordinate.csv') place = dataset[ ['Latitude', 'Longitude'] ] place=place.values.tolist() my_location = geocoder.ip('me') df_text = dataset['Test Lab Name'] xlat = dataset['Latitude'].tolist() xlon = dataset['Longitude'].tolist() locations = list(zip(xlat, xlon)) map2 = folium.Map(location=my_location.latlng, tiles='CartoDB dark_matter', zoom_start=8) marker_cluster = MarkerCluster().add_to(map2) title_html = ''' <style> .button3 {border-radius: 8px;} .button { background-color: #4CAF50; /* Green */ border: none; color: white; padding: 15px 32px; text-align: center; margin-left: 42%; margin-bottom: 10px; text-decoration: none; display: inline-block; font-size: 16px; } </style> <h3 align="center" style="font-size:20px"><b>Covid-19 Active Test Lab In India</b></h3> ''' map2.get_root().html.add_child(folium.Element(title_html)) folium.Marker( location=my_location.latlng, popup='Me', icon=folium.Icon(color='darkblue', icon_color='white', icon='male', angle=0, prefix='fa') ).add_to(map2) try: for point in range(0, len(locations)): folium.Marker(locations[point], popup = folium.Popup(df_text[point]), ).add_to(marker_cluster) except: pass #map2.save('map.html') #bot = Coronavirus() #bot.get_data() total_case = '343,026' total_death = '9,915' total_recovere = '180,320' return render_template('map.html', total_cases=total_case, total_deaths=total_death, total_recovered=total_recovere)
def add_legend(my_map, month): item_txt = """<br> {item} <i class="fa fa-map-marker fa-2x" style="color:{col}"></i>""" html_itms = "" for color, text in zip( ["blue", "green", "orange", "red", "grey"], ["Max ≤ 18", "18 < Max ≤ 24", "24 < Max ≤ 30", "Max > 30"]): html_itms += item_txt.format(item=text, col=color) legend_html = """ <div style=" position: fixed; bottom: 50px; left: 50px; width: 120px; height: 100px; border:2px solid grey; z-index:9999; background-color:white; opacity: .85; font-size:10px; font-weight: bold; "> {title} {itm_txt} </div> """.format(title="Month: " + month, itm_txt=html_itms) my_map.get_root().html.add_child(folium.Element(legend_html)) return my_map
def render_map(lat_long_list, zoom_level=13): counter = 0 try: if len(lat_long_list) > 0: my_map = folium.Map([lat_long_list[0][0], lat_long_list[0][1]], zoom_start=zoom_level) for lat_long in lat_long_list: counter = counter+1 my_map.add_child(folium.Marker([lat_long[0], lat_long[1]], popup=lat_long[2]+"_"+str(counter), icon=folium.Icon(color=catogery_mapper(lat_long[2]), prefix='fa', icon='circle'))) legend_html = """ <div style=”position: fixed; bottom: 50px; left: 50px; width: 100px; height: 90px; border:2px solid grey; z-index:9999; font-size:14px; “> Cool Legend <br> East <i class=”fa fa-map-marker fa-2x” style=”color:green”></i><br> West <i class=”fa fa-map-marker fa-2x” style=”color:red”></i> </div> """ return my_map.get_root().html.add_child(folium.Element(legend_html)) except: raise Exception
def title(m, x): loc = x title_html = ''' <h3 align="center" style="font-size:16px"><b>{}</b></h3> '''.format(loc) m.get_root().html.add_child(folium.Element(title_html)) return m
def map_runs(unique_coordinates): '''Takes in a list of coordinates for running routesand returns the html for the folium map with routes plotted in different colors.''' #get start point for the map print("unique_coordinates[0][0]: ", unique_coordinates[0][0]) #checking outputs lat, long = unique_coordinates[0][0] m = folium.Map(location=[lat, long], zoom_start=12.3) for idx, route in enumerate(unique_coordinates[0:5]): colors = ['blue','green','red','orange','purple'] folium.PolyLine( route, weight=2, color=colors[idx] ).add_to(m) #create legend for colors to route number legend_html = '''<div style= "position: fixed; bottom: 50px; left: 50px; width: 100px; height: 180px; border:2px solid grey; z-index:9999; font-size:14px; "> Routes <br> Route 1 <i class="fa fa-square fa-2x" style="color:blue"></i><br> Route 2 <i class="fa fa-square fa-2x" style="color:green"></i> Route 3 <i class="fa fa-square fa-2x" style="color:red"></i><br> Route 4 <i class="fa fa-square fa-2x" style="color:orange"></i> Route 5 <i class="fa fa-square fa-2x" style="color:purple"></i> </div>''' m.get_root().html.add_child(folium.Element(legend_html)) #add legend to map mapdata = BytesIO() m.save(mapdata, close_file=False) html = mapdata.getvalue() return html
def visualize_locations(filename, location_prototype, location_features, tiles='stamentoner', zoom_start=11, q=np.array([0.0, 0.25, 0.50, 0.75, 1.0])): global c_lat, c_lon if c_lat is None: points = np.array([[p[1], p[0]] for p in location_prototype.values()]) c_lat, c_lon = np.mean(points, axis=0) lat_list = list() lon_list = list() sup_list = list() for lid, p in location_prototype.items(): lat_list.append(p[1]) lon_list.append(p[0]) sup_list.append(np.sqrt(location_features[lid]['loc_support'] * 10000)) sup_colors = pd.qcut(sup_list, q=q, duplicates='drop') colors = list(cl.scales['9']['seq']['Blues'])[9 - len(sup_colors.categories):] sup_colors = pd.qcut(sup_list, q=q, labels=colors, duplicates='drop') m = folium.Map(location=[c_lon, c_lat], tiles=tiles, zoom_start=zoom_start) for i in range(0, len(location_prototype)): folium.Circle( location=(lat_list[i], lon_list[i]), radius=sup_list[i], color=sup_colors[i], fill=True, fill_color=sup_colors[i], fill_opacity=0.8 ).add_to(m) title_html = """<div style="position: fixed; top: 20px; left: 50px; width: 800px; height: 90px; z-index:9999; font-size:40px; font-weight:bold; color: #3175b7">Detected Locations</div>""" m.get_root().html.add_child(folium.Element(title_html)) m.save(filename) webbrowser.open('file://%s' % filename)
def visualizacion_mapa(conn): datos, columnas = base_de_datos.mejor_resultado(conn) df = gpd.GeoDataFrame(datos, columns=columnas) df['punto_coordenada'] = df['punto_coordenada'].apply(wkt.loads) df.set_geometry('punto_coordenada', inplace=True, crs='EPSG:4326') coordenadas_aprox_centro_caba= [-34.615016, -58.441922] nro_generaciones = df['generacion_nro'].unique().tolist() for i in (nro_generaciones): df_temp = df[df['generacion_nro']==i] titulo = 'Generacion {}'.format(i) title_html = ''' <h3 align="center" style="font-size:16px"><b>{}</b></h3> '''.format(titulo) map = folium.Map(coordenadas_aprox_centro_caba, zoom_start=12) map.get_root().html.add_child(folium.Element(title_html)) for j in range(0, len(df_temp)): folium.Circle( location=[df_temp['punto_coordenada'].iloc[j].y, df_temp['punto_coordenada'].iloc[j].x], radius=15, fill=True, color='crimson',).add_to(map) del df_temp map.save('mapa_generacion_{}.html'.format(i))
def visualize_stops(filename, trajectories, tiles='stamentoner', zoom_start=11, radius=50): global c_lat, c_lon if c_lat is None: points = np.array([[traj.start_point()[1], traj.start_point()[0]] for traj in trajectories.values()]) c_lat, c_lon = np.mean(points, axis=0) lat_list = list() lon_list = list() for tid, traj in trajectories.items(): lat_list.append(traj.object[-1][1]) lon_list.append(traj.object[-1][0]) m = folium.Map(location=[c_lon, c_lat], tiles=tiles, zoom_start=zoom_start) for i in range(0, len(trajectories)): folium.Circle(location=(lat_list[i], lon_list[i]), radius=radius, fill=True, fill_opacity=0.8).add_to(m) title_html = """<div style="position: fixed; top: 20px; left: 50px; width: 800px; height: 90px; z-index:9999; font-size:40px; font-weight:bold; color: #3175b7">Stop Points</div>""" m.get_root().html.add_child(folium.Element(title_html)) m.save(filename) webbrowser.open('file://%s' % filename)
def folium_add_map_title(title: str, folium_map: folium.Map): """Adds a map title""" html = ''' <div style=”position: fixed; bottom: 50px; left: 50px; width: 100px; height: 90px; border:2px solid grey; z-index:9999; font-size:10pt; “>{}</div>'''.format(title) folium_map.get_root().html.add_child(folium.Element(html))
def map_cuad(crimes, cuadrante, name_plot, latitude, longitude, pol_station): ''' Creates map of a given precinct with markers of crimes ocurred in that area. Inputs: crimes: filtered data frame cuadrante(int): id of the oprecinct to map name_plot(str): name of the map latitude(int): introduced bu the user longitude(int): introduced by the user pol_station(tuple): (latitude, longitude, distance) of nearest police station ''' m = folium.Map(location=[latitude, longitude], zoom_start=16, color='RGBA') folium.GeoJson(cuadrante).add_to(m) for crime in crimes.iterrows(): popup = crime[1].delito folium.Marker(location=[crime[1].latitud, crime[1].longitud], popup=popup, icon=folium.Icon(color='blue', icon='info-sign'), tooltip='Reported Crime!').add_to(m) folium.Marker( location=[latitude, longitude], popup='To find nearest police station folllow the green line', icon=folium.Icon(color='red', icon='home'), tooltip='Your Address').add_to(m) folium.Marker(location=[pol_station[0], pol_station[1]], popup='Nearest Police station:' + ' {:.2f} kilometers'.format(pol_station[2]), icon=folium.Icon(color='green', icon='cloud'), tooltip='Police station').add_to(m) points = [[latitude, longitude], [pol_station[0], pol_station[1]]] folium.PolyLine(points, color="green", weight=2.5, opacity=1).add_to(m) legend_html = """ <div style='position: fixed; bottom: 10px; left: 10px; width: 130px; height: 100px; border:2px solid black; z-index:9999; font-size:12px; background-color:white; '> Legend <br> Your Address <i class='fa fa-map-marker fa-2x' style='color:red'></i><br> Police Station <i class='fa fa-map-marker fa-2x' style='color:green'></i><br> Reported Crime <i class='fa fa-map-marker fa-2x' style='color:DeepSkyBlue'></i><br> </div> """ m.get_root().html.add_child(folium.Element(legend_html)) m.save(name_plot)
def get_map_sat_id(sat_id_i, sat_name_i, sat_period_i): utc_time_now = datetime.utcnow() utc_time_now_str = utc_time_now.strftime('%Y-%m-%d %H:%M:%S') #print(utc_time_now) #вытащим данные о движении для этого спутника sql = '''select * from satellite.space s where s.SAT_ID = {};'''.format( sat_id_i) data = client.execute(sql) df_i = pd.DataFrame(data, columns=['sat_id', 'i', 'utctime', 'lat', 'lon']) #найдем ближайшую точку к текущему времени, чтобы отобразить на карте near_data_i = sorted(df_i['utctime'], key=lambda x: abs(x - utc_time_now))[:1] near_point = df_i[df_i['utctime'] == near_data_i[0]] #print('Ближайшая рассчитанная точка спутника к текущему времени: ' + str(near_point) + ' для ' + str(utc_time_now)) # построим карту data = df_i lat = data['lat'] lon = data['lon'] time = data['utctime'] reg = re.compile('[^a-zA-Z0-9() ]') sat_name_i_good = reg.sub('', sat_name_i) loc = 'MAP for satellite "' + sat_name_i + '" on UTC ' + str( utc_time_now_str) + ' with period = ' + str(int(sat_period_i)) + ' min' title_html = ''' <h3 align="center" style="font-size:16px"><b>{}</b></h3> '''.format(loc) map = folium.Map(zoom_start=1, titles=title_html) for lat, lon, time in zip(lat, lon, time): folium.CircleMarker(location=[lat, lon], radius=3, popup=str(time), min_width=14, fill_color='blue' ''', color="gray" ''', fill_opacity=0.8).add_to(map) folium.PolyLine(data[['lat', 'lon']], color="gray", weight=1, opacity=1, smooth_factor=0.5).add_to(map) folium.CircleMarker(location=near_point[['lat', 'lon']], radius=15, min_width=14, fill_color='', fill_opacity=1, popup='<b>' + str(near_point.iloc[0]['utctime']) + '<b/>').add_to(map) map.get_root().html.add_child(folium.Element(title_html)) map.save('../image_out/' + sat_name_i_good + ".html") display(map) return
def add_title(map_name, country, your_name): title_html = ''' <h2 align="center" style="font-size:20px"><b>Coronavirus Total Confirmed Cases in {}</b></h2> <h4 align="center" style="font-size:16px"><i>Created by</i> {}</h4> <h4 align="center" style="font-size:16px"><i>Powered by</i> <a href="https://www.whitehatjr.com/">WhiteHat Jr</a> </h4> '''.format(country, your_name.upper()) return map_name.get_root().html.add_child(folium.Element(title_html))
def plot_number_of_cases(self): for recovered_date in self.dates: self.plot_by_regions(self.dates[recovered_date]) all_dates = list(self.dates.keys()) all_dates.sort() self.map.get_root().html.add_child( folium.Element( legend_html_template.format(date_first=all_dates[0], date_last=all_dates[-1])))
def set_up(df): def add_marker(lat,long,typeof): folium.Marker(location=[lat,long],popup=folium.Popup(typeof,parse_html=True), icon=folium.Icon(get_color(typeof)))\ .add_to(get_ftype(typeof)) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def get_ftype(typeof): typeof2 = typeof.replace(' ','') if typeof2 in type_dict: return type_dict[typeof2] else: return type_dict['other'] # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def get_color(typeof): typeof2 = typeof.replace(' ','') if typeof2 in type_color_dict: return type_color_dict[typeof2] else: return type_color_dict['other'] # Singapore fmap=folium.Map(location=[1.349, 103.748], zoom_start=12) #fmap=folium.Map(location=[0, 0], zoom_start= 4) fgam = folium.FeatureGroup(name='Adult Mozzies') fglm = folium.FeatureGroup(name='Mozzi Larvae') fgsw = folium.FeatureGroup(name='Still Water') fgem = folium.FeatureGroup(name='Mozzi Eggs') fmap.add_child(fgam) fmap.add_child(fgem) fmap.add_child(fglm) fmap.add_child(fgsw) fmap.add_child(folium.LayerControl()) legend_html = ''' <div style="position: fixed; background-color: white; bottom: 50px; left: 50px; width: 180px; height: 300px; border:2px solid grey; z-index:9999; font-size:14px; "> <br> <b> Legend</b> <br> <table style="width:100%"> <tr><td> Adult Mozzi </td><td> <i class="fa fa-map-marker fa-2x" style="color:blue"></i></td></tr> <tr><td> Mozzi Larvae </td><td><i class="fa fa-map-marker fa-2x" style="color:green"></i></td></tr> <tr><td> Mozzi Eggs </td><td><i class="fa fa-map-marker fa-2x" style="color:orange"></i></td></tr> <tr><td> Still Water </td><td><i class="fa fa-map-marker fa-2x" style="color:red"></i></td></tr> </table> </div> ''' fmap.get_root().html.add_child(folium.Element(legend_html)) type_dict = {'AdultMosquito':fgam,'MosquitoLarva':fglm,'MosquitoEggs':fgem,'other': fgsw} type_color_dict = {'AdultMosquito':'blue','MosquitoLarva':'green','MosquitoEggs':'orange','other': 'red'} for row in df.itertuples(): add_marker(row.lat,row.long,row.typeof) fmap.save('templates/Map.html')
def create_map(): CODA = CovidData() CODA.merge_data_and_coordinates() CODA.drop_rows_with_missing_info() CODA.select_last_date() CODA.plot_departments(CODA.merged_data_last, 'grey') CODA.map.get_root().html.add_child(folium.Element(legend_html)) colormap.caption = 'COVID-19 death toll per department (Source: opencovid19-fr)' CODA.map.add_child(colormap) return CODA
def delta0(LAT, LON): loc = 'You are Safe' title_html = '''<h3 align="center" style="font-size:26px"><b>{}</b></h3>'''.format( loc) o = folium.Map(location=[LAT, LON], zoom_start=11, zoom_control=False, scrollWheelZoom=False, dragging=False) o.get_root().html.add_child(folium.Element(title_html)) o.save('templates/map-with-title.html')
def create_map(): # Get the district shapefile and the list of projects that have already been spatially joined to the appropriate congressional district geo_df, projs = get_cd116() # Loop through each district shape # and use the district name to filter the list of projects # to build a map of projects in that district; for i, row in geo_df.iterrows(): #for i, row in nsd.iterrows(): marker_array = [] tmp_df = geo_df[geo_df['district'] == row['district']] tmp_projs = projs[projs['cd116'] == row['district']] print(tmp_projs.head()) # Hawaii's get bounds function is far too wide/large for the state or district, so set bound explicitly # This is not a great way to do this, but works as a first step. # Next step would be to build a dictionary of these bounds that can be filtered by district # Would need to examine each of the districts, perhaps exporting each of the bounds temporarily # in the code below to build a base version if(row['district'] == 'HI-02'): x1 = -160.678701 y1 = 18.927830 x2 = -154.724111 y2 = 22.360977 else: x1, y1, x2, y2 = tmp_df['geom'].iloc[0].bounds print(f"x1: {x1} y1: {y1} x2: {x2} y2: {y2}") # For the base map, use the Mapbox api to access our typical styled tiles map = folium.Map(location=[45.5236, -122.6750], tiles="https://api.mapbox.com/styles/v1/aaronleeh/cjr11cc8j1r602sp26k42ckh9/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1IjoiYWFyb25sZWVoIiwiYSI6IjF0SjNqUUUifQ.0sVfP4L9LWoycJoinMovtA", #API_key='pk.eyJ1IjoiYWFyb25sZWVoIiwiYSI6IjF0SjNqUUUifQ.0sVfP4L9LWoycJoinMovtA', attr="SEIA", zoom_control=False) # Color the district shape to provide a visual reference of the geography folium.Choropleth(geo_str=tmp_df, fill_color='#ffe148', fill_opacity=0.7, geo_data=tmp_df, line_opacity=1, line_color="#ffe148").add_to(map) # Loop through the project data and assign the color and radius based on # the project's status for fill color and capacity for circle radius for i, prow in tmp_projs.iterrows(): marker = makeMarker(prow['status_main'], prow['capacity_seia_mw'], [prow['lat'], prow['lon']]) marker.add_to(map) marker_array.append(marker) legend = getLegend() map.get_root().html.add_child(folium.Element(legend)) #map.get_root().html.add_child(folium.Element(legendCSS())) map.fit_bounds([[y1, x1], [y2, x2]]) map.save(linux_dir + f"html/{row['district']}.html") return
def visualize_points(filename, points, tiles='stamentoner', zoom_start=11): global c_lat, c_lon c_lat, c_lon = np.mean(points, axis=0) m = folium.Map(location=[c_lon, c_lat], tiles=tiles, zoom_start=zoom_start) HeatMap(np.c_[points[:, 1], points[:, 0]], min_opacity=0.5, max_zoom=15, max_val=1.0, radius=15, blur=15).add_to(m) title_html = """<div style="position: fixed; top: 20px; left: 50px; width: 800px; height: 90px; z-index:9999; font-size:40px; font-weight:bold; color: #3175b7">Raw GPS Points</div>""" m.get_root().html.add_child(folium.Element(title_html)) m.save(filename) webbrowser.open('file://%s' % filename)
def createLegend(map,data,colors): legend_html = '''<div style="position: fixed; bottom: 50px; left: 50px; width: 400px; height: 200px; border:2px blue; z-index:9999; font-size:16px; "> Legend <br>''' legend_attr = [] for i in range(len(data.unique())): legend_html += ''' {} <i class="fa fa-map-marker fa-2x" style="color:{}"></i><br>''' legend_attr.append(data.unique()[i]) legend_attr.append(colors[i]) legend_html += '''</div>''' legend_html = legend_html.format(*legend_attr) map.get_root().html.add_child(folium.Element(legend_html))
def daily_plotter(df, day, time_column_name='start_time', latitude_columns_name='latitude', longitude_column_name='longitude', visualize_column_name='total_encounters', low_threshold=0, medium_threshold=6, high_threshold=28): lat = 35.162240 lon = -89.926420 latitude = lat longitude = lon m = folium.Map( [latitude, longitude], zoom_start=10, tiles='https://odin.md2k.org/mcontain_map/tile/{z}/{x}/{y}.png', attr="toner-bcg") for lat, lan, intensity in zip(df[latitude_columns_name], df[longitude_column_name], df[visualize_column_name]): folium.Marker( location=[lat, lan], icon=folium.features.CustomIcon( icon_image=color_daily(intensity=intensity, low_threshold=low_threshold, medium_threshold=medium_threshold, high_threshold=high_threshold)), icon_anchor=[12.5, 41]).add_to(m) html_element = ''' <div style="position: absolute; text-align: right; top: 10px; right: 10px; height: 150px; z-index:9999;font-size:14px; font-weight:bold; ">{}<br> </div> <div style="position: absolute; text-align: right; bottom: 15px; right: 10px; z-index:9999; font-size:14px;font-weight:500; "> 28 & Up <i class="fa fa-map-marker fa-2x" style="color:#CB2B3E"></i> <br> 6 - 27 <i class="fa fa-map-marker fa-2x" style="color:#FFD326"></i><br> </div> '''.format("Last updated<br>" + str(day)) m.get_root().html.add_child(folium.Element(html_element)) return m
def draw(self): """ Gera um mapa topojson a partir das opções enviadas """ # http://localhost:5000/charts/choropleth?from_viewconf=S&au=2927408&card_id=mapa_pib_brasil&dimension=socialeconomico&as_image=S analysis_unit = self.options.get('au') # Gets the geometry self.prepare_dataframe() # Join dataframe and state_geo (state_geo, centroid) = self.join_df_geo(self.get_geometry(analysis_unit)) # Creating map instance result = folium.Map(tiles=self.TILES_URL, attr=self.TILES_ATTRIBUTION, control_scale=True) # Generating choropleth layer chart = self.layer_gen(state_geo) # Adding marker to current analysis unit if np.issubdtype(self.dataframe.index.dtype, np.number): analysis_unit = int(analysis_unit) au_row = self.dataframe.loc[analysis_unit] if 'latitude' in list(self.dataframe.columns): centroid = [au_row['latitude'], au_row['longitude']] if centroid: marker_layer = folium.map.FeatureGroup( name=self.get_au_title(au_row, self.options.get('headers')) ) folium.map.Marker( centroid, tooltip=self.tooltip_gen(au_row, self.options.get('headers')), icon=folium.Icon(color=ViewConfReader.get_marker_color(self.options)) ).add_to(marker_layer) marker_layer.add_to(result) chart.add_to(result) folium.LayerControl().add_to(result) result.get_root().header.add_child(folium.Element(self.STYLE_STATEMENT)) # Getting bounds from topojson lower_left = state_geo.get('bbox')[:2] lower_left.reverse() upper_right = state_geo.get('bbox')[2:] upper_right.reverse() # Zooming to bounds result.fit_bounds([lower_left, upper_right]) return result
def visualize_trajectories(filename, trajectories, tiles='stamentoner', zoom_start=11): global c_lat, c_lon if c_lat is None: points = np.array([[traj.start_point()[1], traj.start_point()[0]] for traj in trajectories.values()]) c_lat, c_lon = np.mean(points, axis=0) m = folium.Map(location=[c_lon, c_lat], tiles=tiles, zoom_start=zoom_start) for tid, traj in trajectories.items(): folium.PolyLine([[p[1], p[0]] for p in traj.object]).add_to(m) title_html = """<div style="position: fixed; top: 20px; left: 50px; width: 800px; height: 90px; z-index:9999; font-size:40px; font-weight:bold; color: #3175b7">Reconstructed Trajectories</div>""" m.get_root().html.add_child(folium.Element(title_html)) m.save(filename) webbrowser.open('file://%s' % filename)
def add_info(tweets_map, args, geo_tweets): """Add contextual info to the map: legend title, timestamp, etc.""" if args.custom_title: title = args.custom_title emoji = None elif args_check.input_source(args) == "api" or import_file.has_unique_author( geo_tweets ): title = "@" + geo_tweets[0].user.screen_name emoji = "user" else: title = os.path.basename(args.input_file) emoji = "file" legend_html = display.create_legend(title, emoji) tweets_map.get_root().html.add_child(folium.Element(legend_html)) # HTML <title> tweets_map.get_root().header.add_child( folium.Element("<title>{}</title>".format(display.create_title(title))) ) return tweets_map
def create_map(): CODA = CovidData() CODA.merge_data_and_coordinates() CODA.drop_rows_for_which_confirmed_cases_are_missing() CODA.select_penultimate_date() CODA.select_last_date() CODA.compute_change_in_cases() CODA.plot_departements(CODA.merged_data_diff, 'grey') CODA.map.get_root().html.add_child(folium.Element(legend_html)) colormap.caption = 'Nombre de cas de COVID-19 par departement (Source: opencovid19-fr)' CODA.map.add_child(colormap) return CODA