From f09a5217458ae80377fa86bee217e544ea0e079e Mon Sep 17 00:00:00 2001 From: vladosskins178 Date: Sat, 21 Nov 2026 23:08:09 +0100 Subject: [PATCH] Keep Search layer hidden when show=False L.Control.Search adds its layer to the map in onAdd (setLayer calls layer.addTo(map)), so a layer created with show=False became visible as soon as a Search control was attached to it. Remove the layer again right after the control is added when show is False. Fixes #2377 --- folium/plugins/search.py | 5 +++++ tests/plugins/test_search.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/folium/plugins/search.py b/folium/plugins/search.py index e82876b875..8335c58e7f 100644 --- a/folium/plugins/search.py +++ b/folium/plugins/search.py @@ -88,6 +88,11 @@ class Search(JSCSSMixin, MacroElement): }); }); {{this._parent.get_name()}}.addControl( {{this.layer.get_name()}}searchControl ); + {% if not this.layer.show %} + // L.Control.Search adds its layer to the map when the control is + // added. Remove it again so the layer starts hidden (show=False). + {{this.layer.get_name()}}.remove(); + {% endif %} {% endmacro %} """) # noqa diff --git a/tests/plugins/test_search.py b/tests/plugins/test_search.py index 51542f8823..d1db636959 100644 --- a/tests/plugins/test_search.py +++ b/tests/plugins/test_search.py @@ -24,3 +24,36 @@ 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_keeps_hidden_layer_hidden(): + 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 it must be removed again. + add_control = normalize( + f"{m.get_name()}.addControl( {layer.get_name()}searchControl );" + ) + remove_layer = normalize(f"{layer.get_name()}.remove();") + assert add_control in rendered + assert remove_layer in rendered + assert rendered.index(add_control) < rendered.index(remove_layer) + + +def test_search_does_not_remove_shown_layer(): + m = folium.Map([0, 0], tiles=None) + layer = folium.GeoJson(_geojson_point()).add_to(m) + search = Search(layer, search_label="name").add_to(m) + rendered = normalize(search._template.module.script(search)) + + assert normalize(f"{layer.get_name()}.remove();") not in rendered