Folium, make legend disappear when switching layer (LayerControl)

Viewed 428

I created some legends using the html example by InLaw(1) in this answer. From that answer, I also manage to get this legend using a MacroElement from Branca (2), where template is an html macro template. What I want is that (any) those legends appear and disappear from the map in accordance to a LayerControl.

(1) map.get_root().html.add_child(folium.Element( legend_html ))
(2) macro = MacroElement()
macro._template = Template(template)
m.get_root().add_child(macro)

What have I tried? I tried adding the html and MacroElement to the FeatureLayer or a Choropleth map with no avail. After lurking for a while in the web I found this example that uses java script (I guess, I have -0 experience with JS) to make the bar invisible. But, when I substituted the LinearColormap for any of the above, the legend did not disappear. For example, using the variable macro from (2) I tried this:

m.add_child(BindColormap(FeatureGroup, macro))
m.add_child(BindColormap(Choropleth, macro))

Where FeatureGroup and Choropleth are the names of the variables named like that for simplicity for this example.

I don't know what else I can do.

0 Answers
Related