diff --git a/folium/plugins/search.py b/folium/plugins/search.py index e82876b875..afc8a52842 100644 --- a/folium/plugins/search.py +++ b/folium/plugins/search.py @@ -87,7 +87,14 @@ class Search(JSCSSMixin, MacroElement): return feature.properties.style }); }); + // L.Control.Search adds its layer to the map when the control is + // added. Remove it again if it was not on the map before, e.g. + // show=False or a child of a hidden FeatureGroup. + var {{this.layer.get_name()}}WasOnMap = {{this._parent.get_name()}}.hasLayer( {{this.layer.get_name()}} ); {{this._parent.get_name()}}.addControl( {{this.layer.get_name()}}searchControl ); + if (!{{this.layer.get_name()}}WasOnMap) { + {{this.layer.get_name()}}.remove(); + } {% endmacro %} """) # noqa diff --git a/tests/plugins/test_search.py b/tests/plugins/test_search.py index 51542f8823..da98ee842c 100644 --- a/tests/plugins/test_search.py +++ b/tests/plugins/test_search.py @@ -24,3 +24,33 @@ def test_search_opens_popup_bound_to_geojson_group(): ) in rendered ) + + +def _geojson_point(): + return { + "type": "Feature", + "properties": {"name": "Example"}, + "geometry": {"type": "Point", "coordinates": [0, 0]}, + } + + +def test_search_restores_layer_map_membership(): + m = folium.Map([0, 0], tiles=None) + layer = folium.GeoJson(_geojson_point(), show=False).add_to(m) + search = Search(layer, search_label="name").add_to(m) + rendered = normalize(search._template.module.script(search)) + + # L.Control.Search adds its layer to the map, so a layer that was not on + # the map before must be removed again right after the control is added. + name = layer.get_name() + was_on_map = normalize(f"var {name}WasOnMap = {m.get_name()}.hasLayer( {name} );") + add_control = normalize(f"{m.get_name()}.addControl( {name}searchControl );") + remove_layer = f"if (!{name}WasOnMap) {{{name}.remove();}}" + assert was_on_map in rendered + assert add_control in rendered + assert remove_layer in rendered + assert ( + rendered.index(was_on_map) + < rendered.index(add_control) + < rendered.index(remove_layer) + )