folium icon indicating copy to clipboard operation
folium copied to clipboard

Incorrect behavior for overlay=False with FeatureGroup

Open hhalaby opened this issue 1 year ago • 1 comments

Describe the bug Adding two feature groups to a map with overlay=False in folium==0.14.0 loads the map correctly. One feature group is shown and the other is hidden. image Doing the same in folium folium==0.15.0 loads the map with both feature groups shown. It's only after changing the selected feature group that the other one is hidden

image

To Reproduce

import folium
import geopandas as gpd
import pandas as pd
from folium import GeoJson, LayerControl, Map

gdf_1 = gpd.GeoDataFrame(
    (df1 := pd.DataFrame({"Latitude": [26.48], "Longitude": [-82]})),
    crs="epsg:4326",
    geometry=gpd.points_from_xy(df1.Longitude, df1.Latitude),
)

gdf_2 = gpd.GeoDataFrame(
    (df2 := pd.DataFrame({"Latitude": [26.68], "Longitude": [-81.8]})),
    crs="epsg:4326",
    geometry=gpd.points_from_xy(df2.Longitude, df2.Latitude),
)


base = Map(location=[26.6, -81.9], zoom_start=11, tiles=None)

feature_groups = {
    "group_1": folium.FeatureGroup(name="group_1"),
    "group_2": folium.FeatureGroup(name="group_2"),
}
for fg in feature_groups.values():
    base.add_child(fg)

layer_1 = GeoJson(gdf_1, name="GeoJSON_1")
layer_2 = GeoJson(gdf_2, name="GeoJSON_2")

layer_1.add_to(feature_groups["group_1"])
layer_2.add_to(feature_groups["group_2"])

for id, child in base._children.items():
    if "feature_group" in id:
        child.overlay = False

base.add_child(LayerControl(position="topleft"))

Expected behavior Only one feature group is shown at startup

Environment (please complete the following information):

  • Browser: Chrome
  • Jupyter Notebook or html files? Both
  • Python version 3.10.6
  • folium version 0.15.0
  • branca version 0.7.2

hhalaby avatar Sep 12 '24 13:09 hhalaby

I can probably help out with a solution if someone points me in the right direction !

hhalaby avatar Sep 12 '24 13:09 hhalaby

Looks like this is expected behavior! See https://leafletjs.com/examples/layers-control/:

Also note that when using multiple base layers, only one of them should be added to the map at instantiation, but all of them should be present in the base layers object when creating the layers control.

So it's up to the user to make sure only one base layer is added to the map. In Folium you can use the show parameter for this. So in your example make sure all tile layers and features groups that have overlay=False also have show=False but one.

Conengmo avatar Oct 22 '24 08:10 Conengmo