叶面0.11.0:保持标记层在前面

2024-09-27 02:15:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我想让标记层始终保持在前面,但我不知道如何做到这一点

只要我开始在图层控制窗格中单击和取消单击图层,标记图层就会消失在choropleth图层后面

这是我的代码:

m = folium.Map([40.4165001, -3.7025599], zoom_start=10, tiles='CartoDB Positron', overlay=True)
# folium.TileLayer('cartodbpositron', overlay=True).add_to(m)


income=folium.Choropleth(
    geo_data=censo,
    data=df1,
    name='Household Income 2016',
    columns=['CDSSCC', 'HouseholdIncome2016'],
    key_on='feature.properties.CDSSCC',
    fill_color='BuGn',
    fill_opacity=1,
    line_opacity=0.2,
    highlight=True,
    legend=False,
).add_to(m)

pop=folium.Choropleth(
    geo_data=censo,
    data=df1,
    name='Population 2016',
    columns=['CDSSCC', 'POB_TOTAL'],
    key_on='feature.properties.CDSSCC',
    fill_color='YlOrBr',
    fill_opacity=1,
    line_opacity=0.2,
    highlight=True,
    legend=False,
).add_to(m)

# add clusters to the map
markers_colors = []
for lat, lon, poi, cluster in zip(buildingsmadrid_merged['Latitude'], buildingsmadrid_merged['Longitude'], buildingsmadrid_merged['Name'], buildingsmadrid_merged['Cluster Labels']):
    label = folium.Popup(str(poi) + ' Cluster ' + str(cluster), parse_html=True)
    puntos=folium.CircleMarker(
        [lat, lon],
        radius=5,
        popup=label,
        tooltip = label,
        color='YlOrBr'[cluster-1],
        fill=True,
        fill_color='YlOrBr'[cluster-1],
        fill_opacity=0.7,
        overlay=False).add_to(m)

folium.LayerControl(position='topright', collapsed=False, autoZIndex=True).add_to(m)

# m.save(os.path.join('choropleth.html'))

m

谢谢你的帮助


Tags: to图层addfalsetruedatamergedfill
1条回答
网友
1楼 · 发布于 2024-09-27 02:15:52

Folium用方法m.keep_in_front解决了这个问题

如果保存CircleMarker对象的markers列表,则可以使用m.keep_in_front(*markers)
请注意,项目的顺序将设置它们的优先级,最后是最重要的,尽管我怀疑这在您的情况下是否重要


此解决方案目前仅在覆盖层之间切换时有效。
在基础层之间切换的情况下,这将不起作用

我在尝试在choropleth之间切换时显示工具提示时遇到了类似的问题

我的设置与choropleth层有点不同,choropleth层有overlay=False,因为我更喜欢用单选按钮切换,而且我只有一个层保持在前面

我已经通过以下两个来源解决了这个问题:
A similar question about Leaflet
This issue from the Folium github

自从我切换基本层以来,我使用了eventbaselayerchange

from branca.element import Element

js_keep_in_front = f"""
    {m.get_name()}.on("baselayerchange", function (event) {{
      {popup.get_name()}.bringToFront();
    }});
"""
e = Element(js_keep_in_front)
html = m.get_root()
html.script.get_root().render()
# Insert new element or custom JS
html.script._children[e.get_name()] = e

如果有许多像您的示例中那样的对象,可以将它们分组到folium.FeatureGroup中,如this example中所述,然后使用所述方法将该单层保持在前面

注意在格式化字符串中使用了get_name方法。这很重要,因为您不知道folium将用于地图/图层的名称

相关问题 更多 >

    热门问题