如何在Folium地图绘制无锚点星形标记?已有方形圆形实现方案
解决Folium中绘制不带锚点星形标记的问题
我来帮你搞定这个星形标记的难题!你之前用Font Awesome的star图标出现锚点,是因为这类字体图标默认带有基线锚点,而BeautifyIcon插件又没有内置星形形状。要实现纯星形、无锚点的标记,我们可以通过自定义SVG图标来完美解决。
方案1:使用DivIcon渲染自定义SVG
这种方法直接用SVG定义纯星形,完全控制形状,没有多余元素:
import folium # 创建空地图 m = folium.Map(location=[15, 0], tiles="OpenStreetMap", zoom_start=2) # 方形标记 icon_square = folium.plugins.BeautifyIcon( icon_shape='rectangle-dot', border_color='red', border_width=10, ) folium.Marker([50, -70], tooltip='square', icon=icon_square).add_to(m) # 圆形标记 icon_circle = folium.plugins.BeautifyIcon( icon_shape='circle-dot', border_color='green', border_width=10, ) folium.Marker([-20, 25], tooltip='circle', icon=icon_circle).add_to(m) # 自定义不带锚点的星形标记 star_svg = ''' <svg width="30" height="30" viewBox="0 0 24 24" fill="blue"> <path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/> </svg> ''' # 使用DivIcon渲染自定义SVG icon_star = folium.DivIcon(html=star_svg) folium.Marker([60, 125], tooltip='star', icon=icon_star).add_to(m) m.save('markers_on_folium_map.html')
代码说明:
- 我们定义了一个标准的星形SVG路径,没有任何锚点相关元素,
fill属性设置为你需要的蓝色 folium.DivIcon允许直接传入HTML/SVG代码作为图标,完美适配自定义形状需求- 你可以通过修改SVG的
width、height、fill参数来调整星形的大小和颜色
方案2:用BeautifyIcon包裹SVG(保持风格统一)
如果你想和前两个标记的创建方式保持一致,也可以用BeautifyIcon的html参数来嵌入SVG:
# 替换方案1中的星形部分为以下代码 icon_star = folium.plugins.BeautifyIcon( html='<svg width="30" height="30" viewBox="0 0 24 24" fill="blue"><path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/></svg>', border_color='transparent', # 去掉边框,避免影响星形显示 border_width=0, icon_size=(30, 30) ) folium.Marker([60, 125], tooltip='star', icon=icon_star).add_to(m)
这种方式用BeautifyIcon来承载自定义SVG,和方形、圆形标记的代码风格更统一,同时也能实现无锚点的星形效果。
内容的提问来源于stack exchange,提问作者AjanO




