I created two choropleth layers that I added to a map in folium. However, I don't like the functionality of the layers. First, both legends are displayed even when the layer is not selected. Second, you must manually uncheck the checkbox to view the 2nd choropleth layer by itself.
I would like the legend to only show when its choropleth layer is selected and also allow one choropleth layer to be selected at a time and not allow any overlap.
I looked through the documentation and found what I thought would work which would be adding the choropleth layer to a folium.FeatureGroup()
which I would then add to the map but unfortunately for some reason choropleth layers will return an error when added to a featuregroup.
Next, I came across the overlay paramaeter for choropleth layers. When overlay=False
is added into the choropleth parameter I get a radio button instead of a checkbox which is great but the legends from the other layers are still shown and I lose the tiles from the map.
Below is my code. Any help on this matter would be greatly appreciated. Thank you!
import folium
import pandas as pd
import json
df_theft = pd.read_csv('PA_theft.csv')
df_assualt = pd.read_csv('PA_assualt.csv')
theft_data = json.load(open('theft_geojson.json'))
assualt_data = json.load(open('assualt_geojson.json'))
m = folium.Map(location=[41.20, -77.50], zoom_start=8.3)
theft = folium.Choropleth(
geo_data=theft_data,
data=df_theft,
columns=['county_name', 'rate'],
key_on='feature.properties.county_name',
fill_color='OrRd',
fill_opacity=0.9,
legend_name='Theft incident rate per 100,000 people',
highlight=True,
name='Theft Incidents',
show=True
).add_to(m)
folium.GeoJson(
theft_data,
tooltip=folium.features.GeoJsonTooltip(fields=['county_name', "arrests", "incident_count",
"incident_total", "population", "rate" ],
localize=True)
).add_to(theft.geojson)
assualt = folium.Choropleth(
geo_data=assualt_data,
data=df_assualt,
columns=['county_name', 'rate'],
key_on='feature.properties.county_name',
fill_color='GnBu',
fill_opacity=0.9,
legend_name='Assualt incident rate per 100,000 people',
highlight=True,
name='Assualt Incidents',
show=False
).add_to(m)
folium.GeoJson(
assualt_data,
tooltip=folium.features.GeoJsonTooltip(fields=['county_name', "arrests", "incident_count",
"incident_total", "population", "rate" ],
localize=True)
).add_to(assualt.geojson)
folium.LayerControl(collapsed=False).add_to(m)
m.save('PA_County_Crime_Map.html')
print('Map created.')