【问题标题】:Folium 0.11.0 : Keep markers layer in frontFolium 0.11.0:保持标记层在前面
【发布时间】:2020-05-09 14:47:32
【问题描述】:

我想让标记层始终保持在前面,但我不知道该怎么做。

只要我开始在“图层控制”窗格中单击和取消单击图层,标记图层就会消失在 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

感谢您的帮助

【问题讨论】:

标签: python layer markers folium


【解决方案1】:

Folium 有一个解决方案,方法是 m.keep_in_front

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


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

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

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

我已经设法使用这两个来源解决了这个问题:
A similar question about Leaflet
This issue from the Folium github

自从我切换基础层后,我使用了event baselayerchange

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 将用于地图/图层的名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-26
    • 2019-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    • 2016-05-16
    相关资源
    最近更新 更多