如何在Folium中通过DivIcon制作内置数字的谷歌样式倒水滴形标记
Folium 实现带评分数字的标准倒水滴/尖顶图钉标记
实现逻辑
- 直接借助
folium.DivIcon支持自定义HTML片段的能力,把预先写好的矢量SVG代码直接内嵌到图标中,不需要引入任何外部依赖 - 按谷歌地图常见的倒水滴、常规尖顶图钉的轮廓绘制固定尺寸的SVG图形,预留居中的数字展示区域,完美适配0.0-5.0区间的三位长度评分(个位数+小数点+1位小数)
- 调整图标锚点坐标,让图钉的尖部精准对齐地图经纬度坐标,避免位置错位
- 可根据评分区间自动匹配图钉底色,符合日常地图应用的评分色阶认知
可直接复用的代码实现
import folium def create_rating_marker(rating, lat, lon, marker_type="drop"): # 评分对应的图钉底色,可按需调整色值 if rating <= 2: bg_color = "#e53935" # 低分区:红色 elif rating <= 3.5: bg_color = "#fb8c00" # 中分区:橙色 else: bg_color = "#43a047" # 高分区:绿色 # 两种图钉样式的SVG模板 if marker_type == "drop": # 谷歌标准倒水滴轮廓,尺寸30*42px svg_html = f''' <svg width="30" height="42" viewBox="0 0 30 42" xmlns="http://www.w3.org/2000/svg"> <path d="M15 0C6.7 0 0 6.7 0 15c0 10.5 15 27 15 27s15-16.5 15-27C30 6.7 23.3 0 15 0z" fill="{bg_color}"/> <circle cx="15" cy="15" r="11" fill="white"/> <text x="15" y="19" font-size="11" font-family="Arial, sans-serif" text-anchor="middle" fill="{bg_color}">{rating:.1f}</text> </svg> ''' icon_anchor = (15, 42) icon_size = (30, 42) else: # 常规尖顶图钉轮廓,尺寸28*36px svg_html = f''' <svg width="28" height="36" viewBox="0 0 28 36" xmlns="http://www.w3.org/2000/svg"> <path d="M14 0C6.3 0 0 6.3 0 14c0 8.4 11.2 19.6 13.3 21.4c0.4 0.3 0.9 0.5 1.4 0.5s1-0.2 1.4-0.5C18.8 33.6 28 22.4 28 14C28 6.3 21.7 0 14 0z" fill="{bg_color}"/> <circle cx="14" cy="14" r="10" fill="white"/> <text x="14" y="18" font-size="10" font-family="Arial, sans-serif" text-anchor="middle" fill="{bg_color}">{rating:.1f}</text> </svg> ''' icon_anchor = (14, 36) icon_size = (28, 36) # 生成自定义图标与地图标记 custom_icon = folium.DivIcon( html=svg_html, icon_anchor=icon_anchor, icon_size=icon_size ) return folium.Marker( location=[lat, lon], icon=custom_icon ) # 使用示例 if __name__ == "__main__": # 初始化地图 rating_map = folium.Map(location=[39.9042, 116.4074], zoom_start=12) # 批量添加测试标记 test_points = [ (0.8, 39.89, 116.42), (2.1, 39.91, 116.41), (3.4, 39.92, 116.39), (4.6, 39.90, 116.40) ] for score, lat, lon in test_points: # 切换marker_type="pin"可使用常规尖顶图钉样式 create_rating_marker(score, lat, lon, marker_type="drop").add_to(rating_map) # 导出为可直接打开的HTML地图文件 rating_map.save("rating_map_output.html")
实用调整说明
- 图钉的尺寸、轮廓、颜色可直接修改SVG模板中的对应参数,不需要改动其他逻辑
- 数字显示的字号已经适配三位字符的长度,不会出现文字溢出白色圆形区域的问题
- 所有样式全部内嵌在HTML代码中,不会出现外部资源加载失败导致的标记样式异常
- 若需要调整图钉的投影效果,可在SVG代码中增加阴影滤镜参数,和原生谷歌地图的视觉效果进一步对齐
内容的提问来源于stack exchange,提问作者Steven
相关产品推荐
相关产品推荐

