def draw_balti_border(i_final_map,g1,i_type): #Add chloropleth layer: optional folium.Choropleth( geo_data='baltimore.json', name='choropleth', data=df_neighood, columns=['Name', 'Population'], key_on='feature.properties.name', fill_color='YlGn', fill_opacity=0.4, line_opacity=0.1, legend_name='Population').add_to(i_final_map) #Create Style function for GeoJson method style_function = lambda x: { 'fill_color':'YlGn', 'color':'black', 'weight':0.8, 'line_opacity':0.0, 'fillOpacity': 0.0 } if(i_type=='analysis'): print(i_type) #Create Style function for GeoJson method g1.add_child(folium.GeoJson( df_geojson, style_function=style_function, tooltip=folium.GeoJsonTooltip( fields=['name', 'White','Blk_AfAm','Crime_Count','Police_Count','Detected_Crime_Count'], aliases=['Neighbourhood','White','Blk_AfAm','Crime_Count','Police_Count','Detected_Crime_Count'], localize=True ) )) else: g1.add_child(folium.GeoJson( df_geojson, style_function=style_function, tooltip=folium.GeoJsonTooltip( fields=['name','Male','Female', 'White','Blk_AfAm','AmInd_AkNa','Asian','NatHaw_Pac','Other_Race','TwoOrMore','Hisp_Lat'], aliases=['Neighbourhood','Male Population','Female Population','White','Blk_AfAm','AmInd_AkNa','Asian','NatHaw_Pac','Other_Race','TwoOrMore','Hisp_Lat'], localize=True ) )) i_final_map.add_child(feature_group) i_final_map.add_child(g1) #Inorder to know labels in map while zooming we can use the followig: optional folium.map.CustomPane('labels').add_to(i_final_map) folium.TileLayer('CartoDBPositronOnlyLabels', pane='labels').add_to(i_final_map) return (i_final_map)
def makeSingleFDOutlineMap(output_dir, bg_filepath, fd_filepath, geojson_key, map_filename, data, column, bg_info_col_name, casual_name, color="YlOrRd"): """ Creates choloropleth map of single value with toggleable fire district outlines. Inputs: """ # Change block group to string type for mapping data['Block_Group'] = data['Block_Group'].astype(str) data['Block_Group'] = data['Block_Group'].str[:12] fmap = folium.Map(location=[29.72, -95.60], tiles='cartodbpositron', zoom_start=10) folium.Choropleth(geo_data=bg_filepath, data=data, columns=['Block_Group', column], key_on=geojson_key, name=casual_name+" Map", fill_color=color, fill_opacity=1, line_opacity=0.2, nan_fill_color='White', legend_name=bg_info_col_name).add_to(fmap) style_function = lambda x: {'fillColor': '#ffffff', 'color':'black', 'fillOpacity': 0.1, 'weight': 2} highlight_function = lambda x: {'fillColor': '#000000', 'color':'#000000', 'fillOpacity': 0.30, 'weight': 2} # Create data frame of admin dist to polygon fd_geo_df = gpd.read_file(fd_filepath, driver='GeoJSON') fd_geo_df = fd_geo_df[['Fire_Districts.AdminDist', 'geometry']] # Add block group and fire district outlines folium.GeoJson( fd_geo_df, show=False, style_function = style_function, highlight_function = highlight_function, tooltip=folium.GeoJsonTooltip( fields=['Fire_Districts.AdminDist'], aliases=['District Number'], localize=True ), name='Fire District').add_to(fmap) bg_geo_df = make_bg_geo_data(bg_filepath, data) folium.GeoJson( bg_geo_df, highlight_function=highlight_function, style_function = lambda x: { 'color': 'gray', 'weight': 1, 'fillOpacity': 0 }, tooltip=folium.GeoJsonTooltip( fields=['Block_Group', column], aliases=['Block Group', bg_info_col_name], localize=True ), name='Block Group Information').add_to(fmap) LayerControl(collapsed=False).add_to(fmap) fmap.save(output_dir+"/"+map_filename+".html")
def add_poly_layer(layer_wgs_84, layerName, colorRGB, fl, al, fmap): gjson = layer_wgs_84.to_json() if (layerName == 'Statistical'): # Statistical Borders feature_group = folium.FeatureGroup(name=layerName) style = { 'fillOpacity': 0.0, 'weight': 2, 'fillColor': colorRGB, 'dashArray': '10, 10' } folium.GeoJson( gjson, style_function=lambda x: style).add_to(feature_group) elif (layerName == 'Background Buildings'): # Buildings Background feature_group = folium.FeatureGroup(name=layerName) style = {'fillOpacity': 0.8, 'weight': 0, 'fillColor': colorRGB} folium.GeoJson( gjson, style_function=lambda x: style).add_to(feature_group) elif (layerName == 'Future Plan'): # Polygon Future Plans feature_group = folium.FeatureGroup(name=layerName) style = {'fillOpacity': 0.25, 'weight': 0, 'fillColor': colorRGB} folium.GeoJson(gjson, style_function=lambda x: style, tooltip=folium.GeoJsonTooltip( fields=fl, aliases=al)).add_to(feature_group) elif (layerName == 'Future Buildings'): # Future Buildings Polygon feature_group = folium.FeatureGroup(name=layerName) style = { 'fillOpacity': 0.5, 'weight': 1, 'color': colorRGB, 'fillColor': colorRGB } fl = [ 'Hebrew Address', 'operation', 'FuturePlanID', 'TotalUnits', 'floors', 'Monthly_Mortgage', 'Average_Rent' ] al = [ 'Hebrew Address: ', 'Operation: ', 'Plan ID: ', 'Total Apt: ', 'Floors: ', 'Average Mortgage: ', 'Average Rent: ' ] tooltip = folium.GeoJsonTooltip(fields=fl, aliases=al) geojson = folium.GeoJson(gjson, style_function=lambda x: style, tooltip=folium.GeoJsonTooltip(fields=fl, aliases=al)) geojson.add_to(feature_group) feature_group.add_to(fmap) return fmap
def heatmap(series, geodata, location, fields, aliases, caption, colors=['white','yellow','orange','red','darkred']): if(len(series)==0): style_function=lambda x: { 'fillColor':'white', 'color' : "black", 'weight' : 2, 'fillOpacity': 0.6, } m = folium.Map(location=location, zoom_start=12) stategeo = folium.GeoJson(geodata, style_function=style_function, tooltip=folium.GeoJsonTooltip( fields=['NOMBRE'], aliases=['Comuna'], localize=True )).add_to(m) else: min_cn, max_cn = series[fields[0]].quantile([0.01,0.99]).apply(round, 2) colormap = branca.colormap.LinearColormap( colors=colors, vmin=min_cn, vmax=max_cn ) colormap.caption=caption geodata = geodata.join(series.set_index("comuna"), how = "left", on = "NOMBRE") geodata.fillna(0, inplace = True) m = folium.Map(location=location, zoom_start=12, tiles="OpenStreetMap") style_function = lambda x: { 'fillColor': colormap(x['properties'][fields[0]]), 'color': 'black', 'weight':2, 'fillOpacity':0.6 } stategeo = folium.GeoJson( geodata, name='Teaté Stores', style_function=style_function, tooltip=folium.GeoJsonTooltip( fields=['NOMBRE']+fields, aliases=['Comuna']+aliases, localize=True ) ).add_to(m) colormap.add_to(m) return m
def _get_tooltip(tooltip_col, gpd): """Show everything or columns in the list.""" if tooltip_col is not None: tooltip = folium.GeoJsonTooltip(fields=tooltip_col) else: tooltip = tooltip_col return tooltip
def essential_map(self, map, name, legend, dataset): choro = pd.DataFrame() choro['zip'] = dataset['zip'].astype(str) choro['essentials'] = dataset['result'] # Put percent data on a scale so you can see differences better if (choro['essentials'].max() <= 1 and choro['essentials'].max() > 0.2): print( "Percentages put on a square root scale to visualize differences (see visualization)." ) choro['essentials'] = np.power(choro['essentials'], 1 / 2) * 100 if (choro['essentials'].max() <= 0.2): print( "Percentages all less than 20%, put on a scale to visualize difference (see visualization)." ) choro['essentials'] = np.power(choro['essentials'], 1) * 100 # print(choro['essentials'][50]) tooltip = folium.GeoJsonTooltip(fields=('zip', 'essential')) cLayer = folium.Choropleth(geo_data='nyczip.geojson', data=choro, columns=['zip', 'essentials'], key_on='feature.properties.postalCode', fill_color='OrRd', fill_opacity=.7, legend_name=legend, show=True, highlight=True) cLayer.geojson.add_child(folium.features.GeoJsonTooltip(['postalCode' ])) map.add_child(cLayer) cLayer.layer_name = name
def folium_map(df, x, y, location, countries_topodata, colormap, zoom=1): results_map_income = folium.Map(location, tiles='OpenStreetMap', zoom_start=zoom) #creating dictionary to easily find the UDC voting rate dictionary = df.set_index(x)[y] #clean_data.set_index('CantonID')['UDC'] #Our own choropleth folium.TopoJson( countries_topodata, # open('data/contries.topojson.json'), 'objects.countries1', style_function=lambda x: { 'fillColor': '#black' if (x['id'] not in dictionary.index.values) or (pd.isnull( dictionary[x['id']])) else colormap(dictionary[x['id']]), 'color': 'black', 'weight': 0.5, 'dashArray': '5, 5', 'fillOpacity': 0.9, }, tooltip=folium.GeoJsonTooltip( fields=['name'], aliases=[''], sticky=True, style="font-family: Arial; color: black;", opacity=0.8, direction='top')).add_to(results_map_income) results_map_income.add_child(colormap) #adding legend to map return results_map_income
def main(data_file, polygon_file, resolution, output_file): data = pd.read_csv(data_file).query("~latitude.isnull()") # Index the data by h3. Not the most efficient way to do it but it's fast # enough IMO. data.loc[:, "h3_index"] = [ h3.geo_to_h3(row.latitude, row.longitude, resolution) for _, row in data.iterrows() ] # Read in the US states polygons. us_states = shape(json.load(polygon_file)) state_hexes = set() # Polyfill each state and add it to the big list of h3 indexes. for geometry in us_states: state_hexes |= h3.polyfill(mapping(geometry), resolution, geo_json_conformant=True) all_hexes = state_hexes | set(data.h3_index) # Now reindex the counted sightings by hex address and fill the empties # with zeros. grouped_sightings = (data.groupby("h3_index").agg({ "date": "count" }).reindex(list(all_hexes), fill_value=0)) geo_json = {"type": "FeatureCollection", "features": []} for h3_address, row in grouped_sightings.iterrows(): hexagon = h3.h3_to_geo_boundary(h3_address, geo_json=True) geo_json["features"].append({ "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [hexagon] }, "properties": { "hex_address": h3_address, "count": int(row.date), }, }) # Now it's map time. map_center = [data["latitude"].mean(), data["longitude"].mean()] colormap = branca.colormap.linear.YlOrRd_09.scale( grouped_sightings.date.min(), grouped_sightings.date.max()) m = folium.Map(location=map_center, zoom_start=5, tiles="cartodbpositron") folium.GeoJson( geo_json, tooltip=folium.GeoJsonTooltip(["hex_address", "count"]), style_function=lambda x: { "fillColor": colormap(x["properties"]["count"]), "color": "gray", "weight": 0.1, "fillOpacity": 0.5, }, ).add_to(m) colormap.add_to(m) m.save(output_file)
def map_loads(level): if level == "okres": with open('static\\okresy.json', encoding='utf-8') as myfile: data = myfile.read() elif level == "kraj": with open('static\\kraje.json', encoding='utf-8') as myfile: data = myfile.read() else: with open('static\\slovensko.json', encoding='utf-8') as myfile: data = myfile.read() vis2 = json.loads(data) for zaznam in vis2: debug(zaznam) #print(zaznam['type']) #debug(vis2) # url = ( # "http://download.freemap.sk/AdminLevel" # ) # print(url) # #vis1 = json.loads(requests.get(f"{url}/okresy.json").text) # #vis2 = json.loads(requests.get(f"{url}/okresy-005.json").text) # #http://download.freemap.sk/AdminLevel/kraje.json m = folium.Map(location=[49.0, 19.5], zoom_start=8, width='100%', height='85%') #folium.GeoJson(vis1, name="geojson").add_to(m) g = folium.GeoJson(vis2, name="geojson").add_to(m) folium.GeoJsonTooltip(fields=['TXT']).add_to(g) m.save('templates/map.html') return
def _tooltip_popup(type, fields, gdf, **kwds): """get tooltip or popup""" import folium # specify fields to show in the tooltip if fields is False or fields is None or fields == 0: return None else: if fields is True: fields = gdf.columns.drop(gdf.geometry.name).to_list() elif isinstance(fields, int): fields = gdf.columns.drop(gdf.geometry.name).to_list()[:fields] elif isinstance(fields, str): fields = [fields] for field in ["__plottable_column", "__folium_color"]: if field in fields: fields.remove(field) # Cast fields to str fields = list(map(str, fields)) if type == "tooltip": return folium.GeoJsonTooltip(fields, **kwds) elif type == "popup": return folium.GeoJsonPopup(fields, **kwds)
def testing_with_geo_json_1_entry(): map_with_geo = folium.Map(location=[59.928522, 10.715429], zoom_start=6) path = os.path.join(os.getcwd(), f'demo\geojson_data\one_kommune.json') print(path) geo = folium.GeoJson(path).add_to(map_with_geo) folium.GeoJsonTooltip(fields=['navn']).add_to(geo) folium.LayerControl().add_to(map_with_geo) return map_with_geo
def create_tool_tip(fields, aliases, labels=True): """Create tool tip to add to the map.""" tool = folium.GeoJsonTooltip( fields=fields, aliases=aliases, style=('font-size: 14px;'), labels=labels, ) return tool
def InteractiveMap(geodata, column_name, transport_method, bins): """ Creates an interactive map of the column that you want to visualise using folium. Takes geodataframe, the column name, transport method as a string and the bins for classification (list of numbers that are the upper limit of each class) as parameters. """ #add a basemap m = folium.Map(location=[60.25, 24.8], tiles='cartodbpositron', zoom_start=10, control_scale=True, attribution="Data: Helsinki Travel Time Matrix") #add the choropleth folium.Choropleth( geo_data=geodata, name="Travel times" + transport_method, data=geodata, columns=["YKR_ID", column_name], key_on="feature.properties.YKR_ID", bins=bins, fill_color="RdYlBu", fill_opacity=0.7, line_opacity=0.2, line_color="white", line_weight=0, highlight=True, legend_name="Travel times by " + transport_method + ", in minutes", ).add_to(m) #add tooltips (info when hovering over) as geoJson folium.GeoJson(geodata, name="travel time", smooth_factor=2, style_function=lambda x: { 'weight': 0.01, 'color': '#807e7e', 'fillOpacity': 0 }, highlight_function=lambda x: { 'weight': 1.5, 'color': 'black' }, tooltip=folium.GeoJsonTooltip( fields=["YKR_ID", column_name], labels=True, sticky=False)).add_to(m) #display layer control folium.LayerControl().add_to(m) #save and return the map outfp = "outputs/traveltimes" + transport_method + ".html" m.save(outfp) display(m) return m
def index(): start_coords = (37.49, 127.027) folium_map = folium.Map( # width='100%', # height='75%', min_zoom=7, location=start_coords, zoom_start=11, prefer_canvas=True, ) skorea_provinces = folium.GeoJson( 'user_folium/skorea-provinces-2018-geo.json', name='skorea-provinces', tooltip=folium.GeoJsonTooltip( fields=['name', 'base_year', 'name_eng', 'code'], aliases=['지역', '연도', '영문명', '지역코드'], localize=True ) ) plugins.LocateControl(auto_start=True).add_to(folium_map) # 현재위치로 초기화 skorea_municipalities = folium.GeoJson( 'user_folium/skorea-municipalities-2018-geo.json', name='skorea-municipalities', tooltip=folium.GeoJsonTooltip( fields=['name', 'base_year', 'name_eng', 'code'], aliases=['지역', '연도', '영문명', '지역코드'], localize=True) ) plugins.Search( layer=skorea_provinces, search_label='name', search_zoom=11, placeholder='province' ).add_to(folium_map) plugins.Search( layer=skorea_municipalities, search_label='name', search_zoom=11, placeholder='state' ).add_to(folium_map) # return render_template('v2temp/index.html', map=Markup(folium_map._repr_html_())) return render_template('bootstrap/folium_index.html', map=Markup(folium_map._repr_html_()))
def makeInteractiveMap(output_dir, data, bg_filepath, fd_filepath): fmap = folium.Map(location=[29.72, -95.60], name="Map", tiles='cartodbpositron', zoom_start=10, control=False, overlay=False) for column in columns: data[column] = data[column].round().astype(int) folium_del_legend(folium.Choropleth(geo_data=bg_filepath, overlay=False, show = False, name=column, data=data, threshold_scale = [0, 5, 10, 20, 30, 40, 50, 60, 80, 101], columns=['Block_Group', column], key_on='feature.properties.Name', fill_color='YlOrRd', fill_opacity=1, line_opacity=0.2, nan_fill_color='White', legend_name=column)).add_to(fmap) # Adds a legend - doesn't change existing values though colormap = branca.colormap.linear.YlOrRd_09.scale(0, 90) colormap.caption = 'Proportion out of Total Calls' colormap.add_to(fmap) # Add block group outline with open(bg_filepath) as f: bg = json.load(f) folium.GeoJson( bg, style_function = lambda x: { 'color': 'gray', 'weight': 1, 'fillOpacity': 0 }, name='Block Group Boundaries').add_to(fmap) style_function = lambda x: {'fillColor': '#ffffff', 'color':'black', 'fillOpacity': 0.1, 'weight': 2} highlight_function = lambda x: {'fillColor': '#000000', 'color':'#000000', 'fillOpacity': 0.30, 'weight': 2} # Create data frame of admin dist to polygon fd_geo_df = gpd.read_file(fd_filepath, driver='GeoJSON') fd_geo_df = fd_geo_df[['Fire_Districts.AdminDist', 'geometry']] # Add block group and fire district outlines folium.GeoJson( fd_geo_df, show=False, style_function = style_function, highlight_function = highlight_function, tooltip=folium.GeoJsonTooltip( fields=['Fire_Districts.AdminDist'], aliases=['District Number'], localize=True ), name='Fire District').add_to(fmap) LayerControl(collapsed=False).add_to(fmap) fmap.save(output_dir+"/interactive-map.html")
def create_map(lat, lon, label, infile, fieldname): '''Create a map and write it to index.html ''' jsonfile = infile m = folium.Map(location=[lat, lon], zoom_start=7) # Add some alternate tile layers folium.TileLayer('Stamen Terrain').add_to(m) folium.TileLayer('Stamen Toner').add_to(m) def style_fcn(x): '''The style function can key off x['properties']['NAME10'] which will be strings like 'Senate District 42' but for now, let's just return random colors. ''' return {'fillColor': random_html_color()} def highlight_fcn(x): return {'fillColor': '#ff0000'} gj = folium.GeoJson( jsonfile, name="State %s Boundaries" % label, tooltip=folium.GeoJsonTooltip( fields=[fieldname], # Don't include the field name in the tooltip. # There doesn't seem to be a way to map to # to '10' rather than ' Senate District 10'; # all folium allows is aliasing the field name # and it will add a space even if the alias # is empty. aliases=[''], # Optionally can pass a style # style="font-family: serif;", ), style_function=style_fcn, highlight_function=highlight_fcn) # Here's how to add a popup to the whole GeoJSON object. # gj.add_child(folium.Popup('outline Popup on GeoJSON')) # But it doesn't help in adding a popup that shows the current polygon. # The only way seems to be to add each polygon as a separate feature: # https://stackoverflow.com/a/54738210 # There may eventually be a way to do this: # https://github.com/python-visualization/folium/issues/802 gj.add_to(m) folium.LayerControl().add_to(m) m.save('index.html') print("Saved to index.html")
def CrearMap(limit): cursor = connection.cursor() cursor.execute("show tables") table_names = cursor.fetchall() zip_locations = minidom.parse('CP_14Jal_v2.kml') placemarkers = zip_locations.getElementsByTagName('Placemark') m = folium.Map(location=[20.666667,-103.333333], zoom_start=13) for table in table_names: zip_codes = {} if table[0] == 'primaria': cursor.execute("""SELECT cp, Count(cp) c FROM {0} {1} GROUP BY cp order by c desc LIMIT {2}""".format(table[0], zmg_query, limit)) elif table[0] == 'secundaria' or table[0] == 'preparatoria': cursor.execute("""SELECT codigo_postal, Count(codigo_postal) c FROM {0} {1} GROUP BY codigo_postal order by c desc LIMIT {2}""".format(table[0], zmg_query, limit)) else: continue table_info = cursor.fetchall(); for info in table_info: if zip_codes.get(info[0]) == None: zip_codes[info[0]] = info[1] else: zip_codes[info[0]] += info[1] sorted_codes = [] def IsCPInPlacemarker(marker): cp = getCP(marker) for code in sorted_codes: if code.name == cp: return GeoData(cp, getCoordinates(marker), code.count) for item in zip_codes.items(): sorted_codes.append(ZipCodeCounter(item[0], item[1])) sorted_codes = sorted(sorted_codes, key=lambda x: x.count, reverse=True) geo_list = list(map(IsCPInPlacemarker, placemarkers)) geo_list = [x for x in geo_list if x is not None] f = open('{}.json'.format(table[0]), 'w') f.write(GenerateGeoJson(geo_list)) f.close() style_function = lambda x: {'fillColor': x['properties']['color'] } geo = folium.GeoJson('{}.json'.format(table[0]), name=table[0], style_function=style_function, tooltip=folium.GeoJsonTooltip(fields=['title', 'count'], aliases=['Codigo postal', 'Número de escuelas'])) sorted_codes.clear() geo.add_to(m) folium.LayerControl().add_to(m) m.save(outfile='datamap.html') webbrowser.open('datamap.html')
def plot(self, name, show, boundary_name, colormap): self.logger.debug(f"Merging geo_json on {self.code_name} with {self.CODE_COL} from boundary report") merged_data = self.geo_json.merge(self.map_data, left_on=self.code_name,right_on=self.CODE_COL) self.logger.debug(f"Merged_data\n{merged_data}") folium.GeoJson(merged_data.to_json(), name=name, style_function=lambda x: {'fillColor':self.my_colormap(x['properties'], colormap), 'color':'black','fillOpacity':0.4, 'weight':0.2}, tooltip=folium.GeoJsonTooltip(fields=[boundary_name ,self.SCORE_COL], aliases=['Name', self.display_score_col], localize=True), show=show).add_to(self.map) colormap.add_to(self.map)
def quartier_boundaries(quartiers): return folium.GeoJson( quartiers, name="Quartier boundaries", tooltip=folium.GeoJsonTooltip(["Name"]), style_function=lambda p: { "fillOpacity": "0", "color": "#5B698C", "weight": "1", }, )
def test_geojson_tooltip(): m = folium.Map([30.5, -97.5], zoom_start=10) folium.GeoJson( os.path.join(rootpath, 'kuntarajat.geojson'), tooltip=folium.GeoJsonTooltip(fields=['code', 'name'])).add_to(m) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') m._repr_html_() assert issubclass( w[-1].category, UserWarning), 'GeoJsonTooltip GeometryCollection test failed.'
def create_choropleth_data_layer(layer_name, layer_color, dataframe, dataframe_column_key, dataframe_column, legend_color, map): """ Create data layer for macroeconomic indexes visualizations :param layer_name: :param dataframe: :param dataframe_column: :return: """ data_layer = folium.features.Choropleth(geo_data=geojson_currentWorld, data=dataframe, columns=dataframe_column_key, key_on='feature.properties.name', legend_name=layer_name, fill_color=layer_color, bins=9, nan_fill_color='lightgrey', fill_opacity=0.7, line_opacity=0.2, name=layer_name, overlay=True, highlight=True, show=False) # add data to geojson property for f in data_layer.geojson.data['features']: country = f['properties']['name'] country_value_df_row = dataframe.loc[dataframe['country'] == country][dataframe_column] country_value = extract_df_row_value(country_value_df_row) f['properties'][layer_name] = country_value # create tooltip tooltip_layer_desc = layer_name if ':' not in tooltip_layer_desc: tooltip_layer_desc = ':' + tooltip_layer_desc tooltip_layer_desc = tooltip_layer_desc.split(':')[1] folium.GeoJsonTooltip(fields=['name', layer_name], aliases=['COUNTRY', tooltip_layer_desc ]).add_to(data_layer.geojson) delete_folium_choropleth_legend(data_layer.add_to(m)) # create colormap vmin = min(economics_df[dataframe_column]) vmax = max(economics_df[dataframe_column]) layer_legend = branca.colormap.LinearColormap(legend_color, vmin=vmin, vmax=vmax, caption=layer_name) # bind colormap with chorpleth_layer m.add_child(data_layer) m.add_child(layer_legend) m.add_child(mapBinder.BindColormap(data_layer, layer_legend)) return data_layer
def add_specific_building(self, i, fmap): step_1 = self.updated_bldgs[self.updated_bldgs['FuturePlanID'] == str( self.script_file.loc[i]['FuturePlanID'])] layer = SSI.Convert_2039_2_4326(step_1) #fmap = self.AddLayerChooseView(fmap, layer=specific_bldg_wgs84, lat = lat, lon=lon, zoom=18, option=1) gjson = layer.to_json() style_2 = {'fillOpacity': 0.25, 'weight': 1, 'fillColor': '#ff0000'} tooltip1 = folium.GeoJsonTooltip(fields=['bld_address'], aliases=['Building Address Code']) folium.GeoJson(gjson, style_function=lambda x: style_2, tooltip=tooltip1).add_to(fmap) return (fmap)
def plot_html(): tweetmap = folium.Map(location=[52.54, 13.36], zoom_start=4.25, tiles='CartoDB positron') geoSentiment = folium.GeoJson( TWITTER_GEOJSON, #the actual data / json tile style_function=sent_style, highlight_function=sent_highlight, name='SentimentAnalysis', control=True, tooltip=folium.GeoJsonTooltip( fields=['name'], # style="width:20px;height:20px;background-color:#ffcc00" )) markers = folium.FeatureGroup(name="GeoRegionMarkers") # Loop through data to plot markers for mr, lat, lon, area, sent, ct, ht in zip(marker_region, marker_lat, marker_lon, marker_area, marker_avg_sent, marker_count, marker_hashtags): df = pd.DataFrame( data=[[mr], [sent], [ct], [ht]], columns=['value'], index=['Region', 'Avg. Sent', 'Tweet Count', 'Top Hashtags']) html = df.to_html( classes= 'table table-striped table-hover table-condensed table-responsive') markers.add_child( folium.Circle( location=[lat, lon], radius=area * 100, popup=folium.Popup(html), # tooltip=str(f'avg. sent: {sent}')+ " --", fill_color='#ededed' if sent is None else sent_colorscale(sent), fill=True, color='grey', fill_opacity=0.7)) # add the layers sent_colorscale.add_to(tweetmap) geoSentiment.add_to(tweetmap) tweetmap.add_child(markers) tweetmap.add_child(folium.LayerControl()) return tweetmap
def add_layer(self, layer): """Adds a GeoJSON layer to the Map object. Parameters ---------- layer The layer that needs to be added to the map """ folium.GeoJson(layer, name='Counties\' Overdoses', tooltip=folium.GeoJsonTooltip( fields=['substance', 'county', 'year', 'deaths'], labels=True, sticky=False)).add_to(self)
def india_map(): df_india, gps = load_india_data() # Bins for the confirmed cases: bins = [0, 1, 100, 501, 1001, 3001] my_map3 = folium.Map( #location = [22.9734, 78.6569], location=[19.7515, 75.7139], max_zoom=8, min_zoom=3, zoom_start=4, #width=700, #height=450 ) folium.Choropleth( geo_data=gps, data=df_india, name='Total cases in India (including Foreign National)', columns=[ 'State/UT', 'Total Confirmed cases (including Foreign National)' ], key_on='feature.properties.NAME', bins=bins, fill_color='YlGn', fill_opacity=1, legend_name='Confirmed Cases', highlight=True).add_to(my_map3).geojson.add_child( folium.GeoJsonTooltip(fields=[ 'NAME', 'Total Confirmed cases (including Foreign National)', 'Cured/Discharged/Migrated', 'Death' ], aliases=[ 'State/UT', 'Confirmed Cases', 'Recovered Cases', 'Death Cases' ], localize=True)) df_india["Active"] = df_india[ 'Total Confirmed cases (including Foreign National)'] - df_india[ 'Cured/Discharged/Migrated'] - df_india['Death'] #title_html = ''' # <h4 align="center" style="font-size:17px"><b>Total cases in India (including Foreign National)</b></h4> # <h6 align="center" style="font-size:13px"><i>Hover over the State/UT to check the respective case counts</i></h6>''' #my_map3.get_root().html.add_child(folium.Element(title_html)) my_map3.save('output/India.html') my_map3.save('templates/India.html') return my_map3, df_india
def color_states(m): folium.GeoJson( geo_json_data, style_function=lambda feature: { 'fillColor': linear(feature['properties'][num_killings]), 'color': 'black', 'weight': 2, 'dashArray': '5, 5' }, tooltip=folium.GeoJsonTooltip(fields=[dep_name, num_killings], style="font-family: san serif;", localize=True), highlight_function=lambda x: {'weight': 3, 'fillColor': 'blue'} ).add_to(m)
def plot_map( nome_camada, camada, estilo, campos, ): mapa = folium.Map(location=[-25.5, -49.3], tiles='OpenStreetMap', zoom_start=10) folium.GeoJson(camada, name=nome_camada, tooltip=folium.GeoJsonTooltip(fields=campos), style_function=lambda x: estilo).add_to(mapa) folium.LayerControl().add_to(mapa) # Renderizar mapa no streamlit return mapa
def index(): m = folium.Map([3, -75], tiles='cartodbpositron', zoom_start=6) folium.GeoJson( geo_json_data, style_function=lambda feature: { 'fillColor': '#008000', 'color': 'black', 'weight': 2, 'dashArray': '5, 5' }, tooltip=folium.GeoJsonTooltip(fields=[dep_name], style="font-family: san serif;", localize=True), highlight_function=lambda x: {'weight': 3, 'fillColor': 'red'} ).add_to(m) return m._repr_html_()
def scene_download(t1, t2, n=0, s=0): """ use geopandas to check which scene to download. Default to set n = 0 and s = 0. s = 0 means Level 1-C and s = 1 means Level 2-A """ api_products(t1, t2, n) areas = api.to_geodataframe(sentinel.get(s)) tile_center = tile[tile.Id == str(n + 1)].geometry.centroid[0] tile_location = [tile_center.y, tile_center.x] #f, ax = plt.subplots(1) #areas.plot(ax=ax, column='uuid', cmap=None) #tile[tile.Id == str(n+1)].plot(ax=ax) m = folium.Map(location=tile_location, zoom_start=8) folium.GeoJson(tile[tile.Id == str(n + 1)].geometry.to_json(), name='Filtered Tile', smooth_factor=2, style_function=lambda x: { 'color': 'black', 'fillColor': 'transparent', 'weight': 2 }).add_to(m) cols = ['title', 'filename', 'size', 'geometry', 'cloudcoverpercentage'] scene = areas.loc[:, cols] folium.GeoJson(scene.to_json(), name="Downloaded Scene", smooth_factor=2, style_function=lambda x: { 'color': 'red', 'fillColor': 'transparent', 'weight': 2, 'opacity': 0.7 }, tooltip=folium.GeoJsonTooltip( fields=['title', 'size'], aliases=['Title', 'Size (MB)'], labels=True, sticky=True, localize=True)).add_to(m) folium.LayerControl(autoZIndex=False).add_to(m) return m
def add_layer_to_map(swathfile, layername, color): """Adds the input layer to the folium map""" if not os.path.isfile(swathfile): return () geojsonlayer = json.loads(open(swathfile).read()) df = pandas.DataFrame(geojsonlayer) ds = pandas.Series(df.features[0]['properties']) df = ds.to_frame() gj = folium.GeoJson(geojsonlayer, name=layername) gj.add_child(folium.GeoJsonTooltip(fields=["Satellite :", "Sensor :", \ "Orbit height :", "Orbit number :", \ "Acquisition of Signal Local :", "Acquisition of Signal UTC :", \ "Loss of Signal UTC :", "Transit time :", \ "Node :"])) gj.add_to(satellite_map)