def create_map(): df = load_data() latitude = df['latitude'] longitude = df['longitude'] popups = df['comment'] n_rivals = df['n_rivals'] vmax = df['n_rivals'].max() m = folium.Map(location=[55.7522, 37.6156]) marker_cluster = MarkerCluster() marker_cluster.add_to(m) folium.LayerControl().add_to(m) for lat, lon, popup, n_rival in zip(latitude, longitude, popups, n_rivals): if 'Калейдоскоп' in popup: popup = 'burgerking\nг.Москва, Химкинский бульвар, д. 7/23 ТЦ Калейдоскоп, 4 этаж\nКонкурентов: 3' folium.Marker(location=[lat, lon], popup=popup, icon=folium.Icon( color=color_change(n_rival))).add_to(marker_cluster) colormap = StepColormap(['green', 'blue', 'orange', 'red'], vmin=0, vmax=vmax, index=[0, 1, 4, 8, vmax]).scale(0, vmax) today = date.today() colormap.caption = f'Количество конкурентов ({today.strftime("%B, %Y")})' colormap.add_to(m) m.save("Moscow_Map.html")
def BuildMap(velib_op): """ Create and save a folium map with operational velib in Paris and suburbs Args: velib_op (DataFrame): Clean Dataset with [lat, long, Available velib, Nom de la station, Nombre de bornes disponible] columns """ m = folium.Map(location=[48.85, 2.35], tiles='Cartodb Positron', zoom_start=11) marker_cluster = MarkerCluster(name='Velib clustered', overlay=True, control=False, icon_create_function=None) for k, v in velib_op.iterrows(): location = v.lat, v.long marker = folium.Marker(location=location) popup = 'Station:{}<br>Number of Velibs:{}<br>Number of available docks:{}'.format( v['Nom de la station'], v['Available velib'], v['Nombre de bornes disponibles']) folium.Popup(popup).add_to(marker) marker_cluster.add_child(marker) marker_cluster.add_to(m) m.save( "C:/Users/maxen/OneDrive - DXC Production/Industrialized AI Open Badge Boot Camp/3 Build AI Data Pipelines/real-time-velib/real-time-velib-analysis/web-application/templates/map.html" ) return
def get_friends_locations(user_screen_name, bearer_token) -> str: ''' Gets user name from twitter, returns name of file with created html map. ''' data = get_friends_list(user_screen_name, bearer_token) try: info_on_users = [(user['name'], user['location']) for user in data['users']] except KeyError: return None points_to_put_on_map = [(name, get_location(address)) for name, address in info_on_users] points_to_put_on_map = [(name, tuple(map(float, coordinates))) for name, coordinates in points_to_put_on_map if coordinates] locations_map = folium.Map(tiles='stamenterrain') friends = MarkerCluster() for name, coordinates in points_to_put_on_map: folium.Marker(coordinates, popup=name, icon=folium.Icon(color='red')).add_to(friends) friends.add_to(locations_map) return locations_map # folium Map instance
def addMarkers(m, df, variable, unit): normalized = normalize(df[variable]) mc = MarkerCluster(name=variable+unit, options={'spiderfyOnMaxZoom':'False', 'disableClusteringAtZoom' : '4'}) for i in range(len(df)): folium.CircleMarker(location=[df.lat[i], df.lon[i]], radius=(normalized[i] * 10), tooltip='%s: %f%s <br> date: %s' % (variable, df[variable][i], unit, df['time'][i]), color='darkOrange', fill=True).add_to(mc) mc.add_to(m) return m
def add_markers_as_cluster(self, stations_list): """ :param stations_dict: :return: """ fg = self.get_group(name='stations', add_to_map=True, return_group=True) mc = MarkerCluster() for statn_dict in stations_list: if statn_dict.get('stationName') and statn_dict.get( 'wgs84Latitude') and statn_dict.get('wgs84Longitude'): html_obj = self.get_html_object(statn_dict) popup = self.get_popup(html_obj) marker = self.get_marker( [ statn_dict.get('wgs84Latitude'), statn_dict.get('wgs84Longitude') ], popup=popup, icon=folium.Icon( color='blue' if statn_dict.get('stationIdentityTypeKey' ) == 'oceanografisktNummer' else 'green' if statn_dict. get('stationIdentityTypeKey') == 'klimatnummer' else 'red'), tooltip=statn_dict.get('stationName') or 'Click me!') marker.add_to(mc) mc.add_to(fg)
def add_markers_as_cluster(self, list_objs): """ :param list_objs: dictionary of stations.handler.List :param group_name: :return: """ for list_name, item in list_objs.items(): fg = self.get_group(name=list_name, add_to_map=True, return_group=True) mc = MarkerCluster() for idx in range(item.length): html_obj = self.get_html_object(item, idx) popup = self.get_popup(html_obj) marker = self.get_marker( [item.get('lat_dd')[idx], item.get('lon_dd')[idx]], popup=popup, icon=folium.Icon( color='blue' if list_name == 'master' else 'red', icon='map-marker'), tooltip=item.get('statn')[idx] or 'Click me!') marker.add_to(mc) mc.add_to(fg)
def add_radius_circles_as_cluster(self, list_objs): """ :param list_objs: dictionary of stations.handler.List :param group_name: :return: """ for list_name, item in list_objs.items(): fg = self.get_group(name='-'.join([list_name, 'radius']), add_to_map=True, return_group=True) mc = MarkerCluster() check = False for idx in range(item.length): if item.has_attribute('radius'): if item.get('radius')[idx]: check = True folium.Circle( tuple([ item.get('lat_dd')[idx], item.get('lon_dd')[idx] ]), radius=int(item.get('radius')[idx]), fill_color='#3186cc', weight=.5, ).add_to(mc) if check: mc.add_to(fg)
def create_map(): """ Create an OSM-based map with location markers and save it to html file. """ # https://deparkes.co.uk/2016/06/10/folium-map-tiles/ m = folium.Map( location=[0, 0], tiles='Cartodb Positron', zoom_start=1 ) marker_cluster = MarkerCluster( name='CAT Locations', overlay=True, control=False, icon_create_function=None ) locations = get_locations() for k in locations.keys(): location = locations[k]['y'], locations[k]['x'] marker = folium.Marker(location=location) popup = '{0}'.format(k) folium.Popup(popup).add_to(marker) marker_cluster.add_child(marker) marker_cluster.add_to(m) folium.LayerControl().add_to(m) m.save('map.html')
def create_potential_duplicates_map(base_map, near_duplicates: pd.DataFrame): if near_duplicates is None: return marker_cluster = MarkerCluster(control=False) marker_cluster.add_to(base_map) sub_group = FeatureGroupSubGroup(marker_cluster, name='Near-Duplicate Locations', control=True, show=True) # # add markers # ['LocationA', 'NameA', 'coordinatesA', 'LocationB', 'NameB', 'coordinatesB', 'dist_m'] for ix, row in near_duplicates.iterrows(): for is_row_a in [True, False]: dup_location_marker(row, is_row_a).add_to(sub_group) # add lines folium.PolyLine((row.coordinatesA, row.coordinatesB), color="red", weight=2.5, opacity=1).add_to(sub_group) sub_group.add_to(base_map) return None
def create_map(jdata, center_coords): # Loads data from csv into pandas dataframe with open("yelp_businesses.json") as f: jdata = json.loads(f.read()) center_coords = jdata["region"]["center"]["latitude"], \ jdata["region"]["center"]["longitude"] df = pd.read_json(json.dumps(jdata["health"])) df.head(2) # print(df.head(3)) # creates an empty map zoomed in Rome print(center_coords) working_map = folium.Map(location=center_coords, zoom_start=12) # creates a marker cluster cluster = MarkerCluster().add_to(working_map) # Add markers to cluster, iterating over dataframe for index, row in df.iterrows(): folium.Marker( location=[ row["coordinates"]["latitude"], row["coordinates"]["longitude"] ], popup="{0}: {1} stars".format(row["name"], row["rating"]), icon=folium.Icon(color='green', icon='ok-sign'), ).add_to(cluster) cluster.add_to(working_map) display(working_map) working_map.save(outfile="../templates/map.html")
def add_points_AB2(mapobj, gdf, popup_field_list): #Source: https://github.com/python-visualization/folium/pull/376 #Source IMP: https://github.com/python-visualization/folium/blob/master/examples/MarkerCluster.ipynb # Create empty lists to contain the point coordinates and the point pop-up information coords, popups = [], [] # Loop through each record in the GeoDataFrame for i, row in gdf.iterrows(): # Append lat and long coordinates to "coords" list coords.append([row.geometry.y, row.geometry.x]) # Create a string of HTML code used in the IFrame popup # Join together the fields in "popup_field_list" with a linebreak between them label = '<br>'.join([field + ': ' + str(row[field]) for field in popup_field_list]) popups.append(label) icon_create_function = """\ function(cluster) { return L.divIcon({ html: '<b>' + cluster.getChildCount() + '</b>', className: 'marker-cluster marker-cluster-large', iconSize: new L.Point(20, 20) }); }""" marker_cluster = MarkerCluster( locations=coords, popups=popups, name='1000 clustered icons', overlay=True, control=True, icon_create_function=icon_create_function) marker_cluster.add_to(mapobj) folium.LayerControl().add_to(mapobj) return mapobj
def add_clusters(folium_map: folium.Map) -> None: ''' annotate_map: add clustered fatal crash markers to map Parameters: folium_map: map to which markers are to be added as Layer Returns: None Side Effects: Adds markers to input map as a Layer ''' global fatal lat = list(fatal['Crash_Latitude_GDA94']) lng = list(fatal['Crash_Longitude_GDA94']) dead_count = list(fatal['Count_Casualty_Fatality']) crash_nature = list(fatal['Crash_Nature']) crash_type = list(fatal['Crash_Type']) FATAL_MARKER_SIZE = 10 FATAL_MARKER_FILL_OPACITY = 0.25 # create a marker cluster layer clusters = MarkerCluster(name='Clustered Markers', show=False, control=True) # for each fatal crash, add marker to layer # marker is translucent so zoom out will look ok # Note: crash_type not used in this version for marker_y, marker_x, marker_dc, marker_cn, marker_ct in zip( lat, lng, dead_count, crash_nature, crash_type ): circ_mkr = folium.CircleMarker( location=[marker_y, marker_x], radius=FATAL_MARKER_SIZE, color='red', fill=True, fill_color='red', fillOpacity=FATAL_MARKER_FILL_OPACITY, opacity=FATAL_MARKER_FILL_OPACITY, tooltip=f'{marker_dc} Dead', popup=marker_cn, ) circ_mkr.add_to(clusters) # end for # add clustered markers to map clusters.add_to(folium_map) return None
def draw(self): """ Gera um mapa de cluster a partir das opções enviadas """ # http://localhost:5000/charts/cluster?from_viewconf=S&au=2927408&card_id=mapa_prev_estado_cluster&observatory=te&dimension=prevalencia&as_image=N chart_options = self.options.get('chart_options') # TODO - [REMOVE] Used just for debugging # options["headers"] = [ # {'text': 'nm_municipio', "value": 'nm_municipio'}, # {'text': 'te_rgt_agr_sum_vl_indicador', "value": 'te_rgt_agr_sum_vl_indicador'}, # {'text': 'te_rgt_api_calc_min_part', "value": 'te_rgt_api_calc_min_part'}, # {'text': 'te_rgt_api_calc_max_part', "value": 'te_rgt_api_calc_max_part'}, # { # 'text': 'te_rgt_api_calc_ln_norm_pos_part', # "value": 'te_rgt_api_calc_ln_norm_pos_part' # }, # {'text': 'te_res_agr_sum_vl_indicador', "value": 'te_res_agr_sum_vl_indicador'}, # {'text': 'te_res_api_calc_min_part', "value": 'te_res_api_calc_min_part'}, # {'text': 'te_res_api_calc_max_part', "value": 'te_res_api_calc_max_part'}, # { # 'text': 'te_res_api_calc_ln_norm_pos_part', # "value": 'te_rgt_api_calc_ln_norm_pos_part' # }, # {'text': 'te_nat_agr_sum_vl_indicador', "value": 'te_nat_agr_sum_vl_indicador'}, # {'text': 'te_nat_api_calc_min_part', "value": 'te_nat_api_calc_min_part'}, # {'text': 'te_nat_api_calc_max_part', "value": 'te_nat_api_calc_max_part'}, # { # 'text': 'te_nat_api_calc_ln_norm_pos_part', # "value": 'te_nat_api_calc_ln_norm_pos_part' # } # ] result = self.pre_draw(self.get_tooltip_data()) grouped = self.dataframe.groupby( chart_options.get('layer_id', 'cd_indicador')) show = True # Shows only the first layer for group_id, group in grouped: chart = MarkerCluster( locations=group[self.get_location_columns()].values.tolist(), name=ViewConfReader.get_layers_names( self.options.get('headers')).get(group_id), show=show, popups=group['tooltip'].tolist()) show = False chart.add_to(result) result = self.add_au_marker(result, self.options.get('au')) return self.post_adjustments(result)
def addTrackMarkers(m, df, cruise): mc = MarkerCluster(name=cruise, options={ 'spiderfyOnMaxZoom': 'False', 'disableClusteringAtZoom': '4' }) for i in range(len(df)): folium.CircleMarker(location=[df.lat[i], df.lon[i]], radius=(2), color='darkOrange', fill=True).add_to(mc) mc.add_to(m) return m
def gerar_mapa(request): ip = get('https://api.ipify.org').text response1 = DbIpCity.get(ip, api_key='free') #print(response1) m = folium.Map([response1.latitude, response1.longitude], tiles='cartodbpositron', zoom_start=5, prefer_canvas=True) # Minimapa minimap = plugins.MiniMap(toggle_display=True) m.add_child(minimap) # add full screen button to map plugins.Fullscreen(position='topright').add_to(m) # Declaring points of latitude and longitude #my_locations = [(response1.latitude, response1.longitude),(-25.45,-49.34),(-25.45,-49.34)] doc_ref = db.collection('Pegasus').document(u'Exame') docs = doc_ref.get() exp = docs.to_dict() print(exp['Geopoints'][0]) print(exp['Geopoints'][1]) my_locations = [(exp['Geopoints'][0], exp['Geopoints'][1])] marker_cluster = MarkerCluster(my_locations) marker_cluster.add_to(m) #HeatMap(df).add_to(m) m.save('lab/templates/lab/mapa.html') table_file = open('lab/templates/lab/mapa.html') map_lines = table_file.readlines() table_file.close() table_file = open('lab/templates/lab/mapa.html', 'w+') first_lines = [ "{% extends 'lab/base.html'%} \n", #"{% load static %} \n", "{% block content %} \n", "{% if user.is_authenticated %} \n" ] end_lines = ["\n{% endif %}\n", "{% endblock %}"] table_file.writelines(first_lines) table_file.writelines(map_lines) table_file.close() table_file = open('lab/templates/lab/mapa.html', 'a+') table_file.writelines(end_lines) table_file.close() return render(request, 'lab/mapa.html')
def maps(): long = 5.4502821 lat = 45.1695797 ARA = (lat, long) carte = folium.Map(location=ARA, zoom_start=9, tiles='OpenStreetMap') marker_cluster = MarkerCluster().add_to(carte) offres = pd.read_csv("monster.csv") df = offres.fillna(0) for i , row in df.iterrows(): folium.Marker(location = [row['latitude'], row['longitude']], popup = (row["lien"], row["Categorie"],row["Type-contrat"])).add_to(marker_cluster) marker_cluster.add_to(carte) folium.LayerControl().add_to(carte) return carte
def create_center_markers(base_map, centers_df): # cluster_table has columns ['locId', 'latitude', 'longitude', 'cluster_label', 'GeoName'] if centers_df is None: # No pseudo-sectors return None marker_cluster = MarkerCluster(control=False) marker_cluster.add_to(base_map) sub_group = FeatureGroupSubGroup(marker_cluster, name='Pseudo-sector Centers', control=True, show=True) for index, row in centers_df.iterrows(): hname = row['GeoName'] # marker_color = marker_colors.get('Yellow') # marker_size = 10 xpopup = folium.Popup(row.to_frame().to_html()) # options = { # 'isAlphaNumericIcon': True, # 'borderColor': '#00ABDC', # 'textColor': '#00ABDC', # 'innerIconStyle': 'margin-top:0;' # } marker = folium.Marker( location=(row['latitude'], row['longitude']), popup=xpopup, tooltip=hname, icon=folium.plugins.BeautifyIcon( icon='circle', borderColor='#00ABDC', textColor='#00ABDC', innerIconStyle='margin-top:0;' # icon=L.BeautifyIcon.icon(options), # icon_shape='circle-dot', # text_color=srgb_black, # actually icon color # background_color=marker_color, # border_width=marker_size )) marker.add_to(sub_group) sub_group.add_to(base_map) return None
def create_maps () : LAT_GRE = 45.188529 LONG_GRE = 5.724524 maps = folium.Map(location=[LAT_GRE, LONG_GRE],zoom_start=12) marker_cluster= MarkerCluster() for row in df_visu.itertuples(): folium.Marker(location=[row.latitude, row.longitude], popup= f'<a href="{row.lien}">{row.intitule_offre}</a>').add_to(marker_cluster) marker_cluster.add_to(maps) #print(row) # Afficher un périmètre de rayon 15km autour du centre de la carte folium.Circle( radius= 15000, location= [LAT_GRE, LONG_GRE], color= 'darkblue', fill=False, ).add_to(maps) display(maps)
def draw_heat_map(geo_map: Map, requests: dict): show = True requests_list = sorted(requests.items(), key=lambda item: item[0]) for request_type in requests_list: if show: feature_group = FeatureGroup(name=request_type[0], show=True) show = False else: feature_group = FeatureGroup(name=request_type[0], show=False) mc = MarkerCluster() for request in request_type[1]: # print(request[2]) popup_info = 'Request Type: \n' + request[3] + '\nAddress: ' + request[2] mc.add_child(Marker(location=[request[0], request[1]], popup=popup_info)) mc.add_to(feature_group) feature_group.add_to(geo_map) LayerControl().add_to(geo_map)
def folium(dest="docs/folium.html"): """ genreate folium.html """ my_map = Map( location=[43.0645597, 141.3481196], zoom_start=10, width="100%", height="90%", tiles="openstreetmap", ) marker_cluster = MarkerCluster() for _, row in df.iterrows(): lat = row["緯度"] lng = row["経度"] name = row["施設名"] address = row["検索用住所"] data_type = row["データ区分"] popup_html = f""" <h1>{name}</h1> <h2>{address}</h2> <table> <tbody> <tr> <th>緯度</th> <td>{lat}</td> </tr> <tr> <th>経度</th> <td>{lng}</td> </tr> <tr> <th>データ区分</th> <td>{data_type}</td> </tr> </tbody> </table> """ popup = Popup(IFrame(popup_html), min_width=400, max_width=400) Marker(location=[lat, lng], popup=popup, icon=Icon(color="red")).add_to(marker_cluster) marker_cluster.add_to(my_map) my_map.save(dest)
def create_location_markers(base_map, locations_df): # hotspots_df has columns ['locid', 'lat', 'lng', 'name', 'num', 'marker_size'] marker_cluster = MarkerCluster(control=False) marker_cluster.add_to(base_map) sub_group = FeatureGroupSubGroup(marker_cluster, name='Observations', control=True, show=True) marker_colors_by_name = assign_marker_colors(locations_df) color_by_sectors = 'cluster_label' in locations_df.columns for index, row in locations_df.iterrows(): hname = row['Name'] marker_color = marker_color_for_cluster(row['cluster_label']) if color_by_sectors else \ marker_colors_by_name.get(hname) marker_size = 1 xpopup = folium.Popup(make_observation_popup_html(row), max_width=600) # pixels marker = folium.Marker( location=[row['latitude'], row['longitude']], popup=xpopup, tooltip=hname, icon=folium.plugins.BeautifyIcon( prefix='fa', icon='binoculars', # icon_shape='rectangle', # icon='twitter', icon_shape='marker', # icon_size=Point(), text_color=marker_colors.get('Yellow', 'HotPink'), # actually icon color background_color=marker_color, border_width=marker_size, border_color=marker_colors.get('Silver', 'HotPink'))) marker.add_to(sub_group) sub_group.add_to(base_map) return None
def generate_map( file_path: os.path, project_name: str, user_id: int, project_id: int, service_type: str = "mapping", ) -> Any: """Create final map with geo tagged photos.""" # Open json file with open(file_path) as f: _file = json.load(f) # create map zoom point try: lng, lat = _file["features"][0]["geometry"]["coordinates"] except IndexError: lng, lat = [3, 43] # Get info to generate map map_project = Mapping.query.filter_by(project_name=project_name, user_id=user_id).first() map_ = folium.Map(tiles=map_project.tiles, location=[lat, lng], zoom_start=6) mc = MarkerCluster() for i in range(len(_file["features"])): lng, lat = _file["features"][i]["geometry"]["coordinates"] photo = _file["features"][i]["properties"]["photo_location"] # Create Icon photo_location = f"<a href='{photo}' target='_blank'><img src='{photo}' height='250' width='250'></a>" # noqa photo_location += f"""<p style="text-align:center;"> alt. {_file["features"][i]["properties"]["alt"]} mts | {_file["features"][i]["properties"]["date"]}</p>""" popup = folium.Popup(html=photo_location) # folium.() folium.CircleMarker( [lat, lng], popup=popup, radius=6, fill=True, fill_opacity=1, color=map_project.color, class_name="circle", ).add_to(mc) mc.add_to(map_) map_.save( f"{map_project.user.folder_mapping}/{project_name}/delivery/{project_name}.html" ) # REMOVE GEOJSON FILE AFTER CREATE MAP # os.remove(file_path) map_project.download_file = ( f"{map_project.user.folder_mapping}/{project_name}/delivery/{project_name}.zip" ) db.session.add(map_project) db.session.commit() return prepare_to_download(service_type, project_name, project_id, map_project)
maxele.add_to(m) #Add colorbar color_scale = folium.StepColormap(colors_elev, #index=color_domain, vmin=MinVal, vmax=MaxVal, caption= 'Maximum water level from MSL [m]', ) m.add_child(color_scale) # #################### print(' > CO-Ops stations plot') # ssh Observations stations marker_cluster_coops = MarkerCluster(name='CO-OPs observations') marker_cluster_coops.add_to(m) for ssh1, model1 in zip(ssh_observations, model_observations): fname = ssh1._metadata['station_code'] location = ssh1._metadata['lat'], ssh1._metadata['lon'] p = make_plot(ssh1, model1, 'SSH [m]') #p = make_plot(ssh1, ssh1) marker = make_marker(p, location=location, fname=fname) marker.add_to(marker_cluster_coops) #################### if wind_stations: # Wind Observations stations. #marker_clusterw = MarkerCluster(name='Wind observations') #marker_clusterw.add_to(m) for ssh1, model1 in zip(wnd_observs,wnd_models): fname = ssh1._metadata['station_code']
lat = df.loc[i, 'lat'] long = df.loc[i, 'long'] google_link = "https://maps.google.com/?q=" + str(lat) + "," + str(long) + "&ll=" + str(lat) + "," + str(long) + "&z=15" # html: html = """ <h4>{name}</h4> <h3>{stars}</h3> <a href = {google_search} target="_blank">View on Google</a> """.format(name=df.loc[i, "name"], stars='*' * df.loc[i, 'stars_num'], google_search=google_link) # Create marker: m_color = colors[df.loc[i, 'stars_num'] - 1] marker = folium.Marker(location=[lat, long], popup=html, tooltip=df.loc[i, 'name'], icon=folium.Icon(icon='glyphicon-star', color='gray', icon_color=m_color)) # Add marker to relevant cluster (all Japan restaurants three stars): marker_cluster_3star.add_child(marker) # %% SAVE MAP AS HTML # Add clusters to map: marker_cluster_1star.add_to(m) marker_cluster_2star.add_to(m) marker_cluster_3star.add_to(m) # Add layer control folium.LayerControl().add_to(m) m.save('interactive_map.html')
def map_test(request): map = folium.Map(location=[5.273, 16.821], min_zoom=3, max_zoom=12, zoom_start=3, tileSize=32) map._children['openstreetmap'].options['tileSize'] = 512 map._children['openstreetmap'].options['zoomOffset'] = -1 # print('MAP DICT', map.__dict__) # print('DIGGING', map._children['openstreetmap'].show) # icon_create_function = # marker_cluster = MarkerCluster(icon_create_function = ''' # function(cluster) { # return L.divIcon({html: '<b>' + cluster.getChildCount() + '</b>', # className: 'marker-cluster marker-cluster-small', # iconSize: new L.Point(128, 128)}); # } # ''') # icon_create_function = ''' # function(cluster) { # return L.divIcon({html: '<div><span>' + cluster.getChildCount() + '</span></div>', # className: 'marker-cluster marker-cluster-large', # iconSize: new L.Point(128, 128)}); # } # ''' # icon_create_function = ''' # function(cluster) { # return L.DivIcon({ html: '<div><span>' + cluster.getChildCount + '</span></div>', className: 'marker-cluster marker-cluster-medium', iconSize: new L.Point(40, 40) }); # } # ''' # icon_create_function = ''' # function(cluster) { # return L.divIcon({html: cluster.getChildCount(), # className: 'marker-cluster marker-cluster-small', # iconSize: new L.Point(128, 128)}); # } # ''' marker_cluster = MarkerCluster(icon_create_function=icon_create_function) marker_cluster.add_to(map) print('MARKER CLUSTER', marker_cluster.__dict__) feature_dicts = get_feature_dicts() for feature_dict in feature_dicts: icon = folium.features.CustomIcon(feature_dict['icon_link'], icon_size=( 64, 64, )) marker = folium.Marker( [feature_dict['latitude'], feature_dict['longitude']], icon=icon) # print('MARKER DICT', marker.__dict__) marker.add_to(marker_cluster) # tile_layer = map._children['openstreetmap'] # map.remove_layer(tile_layer) # print('AGAIN', map._children['openstreetmap'].options) # tile_layer = folium.raster_layers.TileLayer(tileSize=32).add_to(map) context = { 'map_iframe': map._repr_html_(), 'map_html': map.get_root().render(), } return render(request, 'map/map_test.html', context=context)
def create_sf_crime_viz(): ''' Load and pre-process the San Francisco crime data ''' # Load the crime data df_crime = pd.read_csv( os.path.join(data_dir_path, 'last_week_SF_crimes.csv')) # Drop the rows in which there's no lat lon data df_crime = df_crime[df_crime['latitude'].notna()] df_crime = df_crime[df_crime['longitude'].notna()] # Create popups and their contents popups_list, locations_list = [], [] for _, row in df_crime.iterrows(): # Trim unnecessary information from the timestamp incident_timestamp = row['incident_datetime'] incident_timestamp = incident_timestamp.replace('T', ' ') incident_timestamp = incident_timestamp[:-7] # Create a popup object and append it to the popups array popup_content = '<strong>Timestamp: </strong>' + incident_timestamp + '<br>' \ + '<strong>Day of the week: </strong>' + row['incident_day_of_week'] + '<br>' \ + '<strong>Description: </strong>' + row['incident_description'] popups_list.append(folium.Popup(html=popup_content)) # Get the lat, lon location data and add it to the list locations_list.append(row[['latitude', 'longitude']].to_numpy().tolist()) ''' Initialize the map ''' map_crime = folium.Map(location=[37.773972, -122.431297], zoom_start=11, max_bounds=True, min_zoom=9, max_lat=38.5, max_lon=-122, min_lat=37, min_lon=-123) ''' Create the map content and add it to the map object ''' # Create marker cluster icon_list = [] for _ in range(len(locations_list)): icon_list.append( folium.Icon(icon='exclamation', prefix='fa', color='orange')) marker_cluster = MarkerCluster(locations=locations_list, popups=popups_list, icons=icon_list) marker_cluster.add_to(map_crime) # Create map legend current_timestamp = datetime.now() - timedelta(days=1) week_before = current_timestamp - timedelta(weeks=1) current_timestamp = current_timestamp.strftime('%Y-%m-%d') week_before = week_before.strftime('%Y-%m-%d') template = utils.create_legend(caption='San Francisco crimes between ' + week_before + ' and ' + current_timestamp) macro = MacroElement() macro._template = Template(template) map_crime.get_root().add_child(macro) ''' Save completed map viz to an appropriate folder ''' map_crime.save( os.path.join(script_dir_path, '..', 'webapp', 'templates', 'SF_crime_viz.html')) print('Successfully created the San Francisco crime viz!')
def mapmaker(trailParam): """Create a new folium map with geojson markers. If called with a trailParam, center map to trail and auto open popup""" # load geojson data into a dict file = os.path.join('static', 'trailheadsjson.geojson') with open(file) as data: geo = json.load(data) # load trails and comment ratings from database if the trail has ratings query = (db.session.query(Trail.trailname, func.avg(Comment.rate_good), func.avg(Comment.rate_hard)).join( Comment, Trail.comments).group_by(Trail.trailname)) trails = {} for trailname, rate_good, rate_hard in query: trails[trailname] = (round(rate_good), round(rate_hard)) # if there is a trail parameter, save coords if trailParam: for features in geo['features']: if features['properties']['PrimaryName'] == trailParam: trailParamCoords = features['geometry']["coordinates"] # create map object if not trailParam: m = folium.Map( location=[39.804298, -111.415337], zoom_start=7, attr= '© <a href="www.openstreetmap.org">OpenStreetMap contributors<a>, <a href="https://gis.utah.gov/">Utah AGRC</a>', width='100%', height='100%') tooltip = 'Click for More Info' mc = MarkerCluster() else: m = folium.Map( location=list(reversed(trailParamCoords)), zoom_start=17, attr= '© <a href="www.openstreetmap.org">OpenStreetMap contributors<a>, <a href="https://gis.utah.gov/">Utah AGRC</a>', width='100%', height='100%') tooltip = 'Click for More Info' mc = MarkerCluster() # create markers from geojson dict, add to marker cluster for features in geo['features']: if features['properties']['Comments'] == 'OVPrimaryUseMTB': custom_icon = 'fa-bicycle' custom_color = 'orange' elif features['properties']['Comments'] == 'OVPrimaryUseHIKE': custom_icon = 'fa-male' custom_color = 'green' else: custom_icon = 'fa-arrows' custom_color = 'blue' name = features['properties']['PrimaryName'] coordinates = features['geometry']['coordinates'] popup = popuper(name, trails) folium.Marker(list(reversed(coordinates)), popup=popup, tooltip=tooltip, icon=folium.Icon(color=custom_color, icon=custom_icon, prefix='fa')).add_to(mc) # add marker cluster to map mc.add_to(m) # save map file_save = os.path.join('templates', 'map.html') m.save(file_save)
icon=None, ).add_to(marker_cluster) m.save(DIR + 'manualClusteredMarkers.html') ############################################################################## # Basic globe with rastered map ############################################################################## size = 100 delta = .01 lats = np.random.uniform(37.773972 - delta, 37.773972 + delta, size=size) lons = np.random.uniform(-122.43129 - delta, -122.43129 + delta, size=size) locations = list(zip(lats, lons)) popups = ['lon:{}<br>lat:{}'.format(lon, lat) for (lat, lon) in locations] m = folium.Map(location=[np.mean(lats), np.mean(lons)], tiles='Cartodb Positron', zoom_start=12) marker_cluster = MarkerCluster(locations=locations, popups=popups, name='1000 clustered icons', overlay=True, control=True) marker_cluster.add_to(m) folium.LayerControl().add_to(m) m.save(DIR + 'randomClusteredMarkers.html')
#Remove rows missing lat/long data df.dropna(subset=['latitude', 'longitude'], axis='rows', how='any', inplace=True) #Get the mean latitude and longitude, to set as the center of the map meanLat = df['latitude'].mean() meanLng = df['longitude'].mean() #Create the folium map object wellMap = folium.Map(location=(meanLat, meanLng), zoom_start=8) #Create a marker cluster object which enables a cleaner display of markers marker_cluster = MarkerCluster() marker_cluster.add_to(wellMap) #Add as Clustered Markers for row in df.iterrows(): #Print dots to show progress print('.', end='') #Get the data from the row; it's the 2nd object (1st is the row's index) data = row[1] #Get the row's data that we want lat = data['latitude'] lon = data['longitude'] name = data['Violation Code'] #Create a marker
def markercluster( gdf, weight=None, metric=None, name="layer", tooltip=None, width=950, height=550, location=None, zoom=7, tiles="OpenStreetMap", attr=None, kwargs={}, ): """ Plot a MarkerCluster map out of a geodataframe. Parameters ---------- gdf : GeoDataframe weight : Custom markercluser, Column used to weight the metrics, optional metric : Custom markercluser, Metric for clustering, based on weight column available metrics: ['sum','average'] name : name of the geojson layer, optional, default "layer" width : width of the map, default 950 height : height of the map, default 550 location : center of the map rendered, default centroid of first geometry color : color of your geometries, default blue use random to randomize the colors tooltip : hover box on the map with geometry info, default all columns can be a list of column names zoom : zoom level of the map, default 7 tiles : basemap, default openstreetmap, options ['google','googlesatellite','googlehybrid'] or custom wms attr : Attribution to external basemaps being used, default None style : dict, additional style to geometries Returns ------- m : folium.map """ gpd_copy = _get_lat_lon(gdf.copy()) m = _folium_map(gpd_copy, width, height, location, tiles=tiles, attr=attr, zoom_start=zoom) if weight is None: marker_cluster = MarkerCluster(**kwargs).add_to(m) for index, row in gpd_copy.iterrows(): if tooltip is not None: tooltip_dict = { k: v for k, v in dict(row).items() if k in tooltip } tooltip = "".join([ "<p><b>{}</b> {}</p>".format(keyvalue[0], keyvalue[1]) for keyvalue in list(tooltip_dict.items()) ]) folium.Marker(location=[row["latitude"], row["longitude"]], tooltip=tooltip).add_to(marker_cluster) else: latlong_list = [ list(latlong) for latlong in list( zip(gpd_copy["latitude"], gpd_copy["longitude"])) ] metric_list = list(gpd_copy[weight]) value_weight_pair = tuple([{ "location": l, "metric": met } for l, met in zip(latlong_list, metric_list)]) if metric is None or metric == "average": marker_cluster = MarkerCluster( icon_create_function=average_function) elif metric == "sum": marker_cluster = MarkerCluster(icon_create_function=sum_function) else: raise Exception("Input a valid metric") for marker_item in value_weight_pair: marker = MarkerWithProps( location=marker_item["location"], props={"population": marker_item["metric"]}, ) marker.add_to(marker_cluster) marker_cluster.add_to(m) return m