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

如何在Python的Folium中为热力图添加带权重的标记集群?

解决Folium热力图添加MarkerCluster并显示集群权重的问题

问题原因

plugins.MarkerCluster()不能直接接收[纬度, 经度, 权重]格式的列表,它需要的是folium.Marker对象的集合。直接传入lats_longs会因为参数类型不匹配报错。

解决方案

先把每个带权重的坐标转换成folium.Marker实例,再将这些Marker添加到MarkerCluster中,同时自定义集群图标,显示该集群内的总权重(人数)。

修改后的完整代码:

import folium
from folium.plugins import HeatMap, MarkerCluster

map_obj = folium.Map(location=[39.057880, -77.459930], zoom_start=10)
lats_longs = [
    [38.91072, -77.01666, 1],
    [38.93577, -77.05921, 1],
    [38.92039, -77.03856, 1],
    [38.93684, -77.09312, 1],
    [38.96083, -77.60435, 3],
    [38.74622, -77.48911, 1],
    [39.17396, -77.73253, 1],
    [39.09063, -77.88877, 1],
    [39.10795, -77.78462, 1],
    [38.92919, -77.93868, 1],
    [39.03957, -77.48161, 30],
    [39.00149, -77.51559, 3],
    [38.89222, -77.50983, 3],
    [38.81329, -77.63394, 1],
    [39.13953, -77.65486, 3],
    [39.01413, -77.39991, 1],
    [39.04736, -77.38648, 2],
    [38.96916, -77.46316, 2],
    [38.86936, -77.63979, 1],
    [38.98372, -77.38276, 8],
    [38.9266, -77.39119, 6],
    [39.05227, -77.60358, 6],
    [39.16004, -77.52185, 13],
    [38.96097, -77.34247, 5],
    [38.93112, -77.35139, 4],
    [39.0048, -77.10248, 1],
    [39.00335, -77.03544, 1],
    [39.2569, -76.79174, 1],
    [39.4959, -77.45401, 1],
    [39.36158, -77.66193, 2],
    [38.83726, -77.34201, 2],
    [38.87937, -77.37677, 1],
    [38.75493, -77.31016, 1],
    [38.86296, -77.19387, 1],
    [39.00445, -77.3081, 3],
    [38.89743, -77.25287, 1],
    [38.88659, -77.09473, 3],
    [38.87499, -77.12261, 1],
    [38.89291, -77.07257, 1],
    [38.79007, -77.0812, 1],
    [39.15107, -78.27722, 1],
    [39.17532, -77.97529, 1],
    [37.5844, 77.51805, 1],
    [39.31515, -78.04753, 1],
    [39.25786, -77.86259, 1],
    [39.26838, -77.78963, 1]
]

# 创建MarkerCluster实例,自定义集群图标显示总权重
marker_cluster = MarkerCluster(
    icon_create_function=lambda cluster: folium.Icon(
        icon='user',
        color='blue',
        icon_color='white',
        html=f'<div style="font-size: 12px; font-weight: bold;">{sum(int(marker.popup._children[0]._children["text"].split(": ")[1]) for marker in cluster.markers)}</div>'
    )
).add_to(map_obj)

# 遍历坐标列表,创建Marker并添加到集群
for lat, lng, weight in lats_longs:
    folium.Marker(
        location=[lat, lng],
        popup=f"人数: {weight}"
    ).add_to(marker_cluster)

# 添加热力图
HeatMap(lats_longs).add_to(map_obj)

map_obj.save("heatmap_with_clusters.html")

关键说明

  • Marker转换:遍历lats_longs,为每个坐标创建folium.Marker,弹窗显示该点的权重。
  • 自定义集群图标:通过icon_create_function计算集群内所有Marker的权重总和,将其显示在集群图标上。这里通过解析Marker的popup内容提取权重值并求和。
  • 图层共存:MarkerCluster和HeatMap可以同时添加到地图上,互不影响。

内容的提问来源于stack exchange,提问作者David Szady

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 20:35:11