You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Folium 0.11.0:如何让标记图层始终显示在最上层?

解决标记图层被Choropleth遮挡的问题

首先咱们来拆解问题根源:

  • 你给CircleMarker设置了overlay=False,这会让标记图层变成基础图层(和底图属于同一层级),而Choropleth默认是overlay=True的叠加图层——叠加图层本来就会显示在基础图层上方,所以切换Choropleth时自然会把标记挡住。
  • 另外,LayerControl的autoZIndex=True会自动调整叠加图层的层级顺序,进一步加剧了标记被覆盖的情况。

下面是具体的修复方案:

步骤1:用FeatureGroup统一管理标记并设置高层级偏移

创建一个FeatureGroup来存放所有标记,通过设置z_index_offset为一个较大的数值(比如1000),确保它始终排在其他叠加图层的最上面。

步骤2:修正CircleMarker的overlay参数

把CircleMarker的overlay改成True,让它成为叠加图层,这样才能参与层级排序,让z_index_offset生效。

完整修改后的代码

import folium
# 假设你的censo、df1、buildingsmadrid_merged等数据已正确加载

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

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)

# 创建FeatureGroup管理标记,设置高z_index_offset确保层级最高
marker_group = folium.FeatureGroup(name='Building Clusters', z_index_offset=1000)

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=True  # 修改为True,转为叠加图层
 )
 puntos.add_to(marker_group)  # 添加到FeatureGroup而非直接添加到地图

# 将标记组添加到地图
marker_group.add_to(m)

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

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

额外说明

  • z_index_offset的数值只要比其他叠加图层的默认值大就行,1000足够覆盖绝大多数场景。
  • 把标记放进FeatureGroup后,你还能在LayerControl里单独控制标记图层的显示/隐藏,灵活性更高。
  • 如果不需要单独控制标记,也可以直接给每个CircleMarker设置z_index_offset=1000,但用FeatureGroup管理会更简洁。

内容的提问来源于stack exchange,提问作者Marta Bescansa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 15:08:12