Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions folium/plugins/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
30 changes: 30 additions & 0 deletions tests/plugins/test_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
)