如何为Leaflet创建内嵌SVG且带圆形边框的自定义标记图标
核心解决方案
修改后CSS代码
.marker-pin { width: 30px; height: 30px; border-radius: 50% 50% 50% 0; background: green; position: absolute; transform: rotate(-45deg); left: 50%; top: 50%; margin: -15px 0 0 -15px; padding: 3px; } /* 内层白色圆形 */ .marker-pin::after { content: ''; width: 24px; height: 24px; background: #fff; position: absolute; border-radius: 50%; z-index: 0; } /* 修正SVG显示样式 */ .marker-pin svg { transform: rotate(45deg); width: 24px; height: 24px; position: relative; z-index: 1; }
修改后HTML片段
移除了SVG自带的背景样式,避免遮挡:
<div class='marker-pin'> <svg class="material-icons custom-div-icon" enable-background="new 0 0 396.079 396.079" version="1.1" viewBox="0 0 396.08 396.08" xml:space="preserve" xmlns="http://www.w3.org/2000/svg"> <path d="m368.74 147.22c7.356-18.313 7.362-36.373-1.709-48.867-16.381-22.556-56.126-18.441-88.78 9.187-32.935 27.868-37.662 71.655-34.661 80.346 2.68 8.795 32.242 41.438 75.267 44.629 42.656 3.157 77.229-16.876 77.225-44.753-5e-3 -15.444-10.625-30.052-27.342-40.542z"/> <path d="m313.31 249.57c-36.682-22.711-79.787-13.676-87.125-8.136-7.535 5.267-29.447 43.469-19.186 85.374 10.18 41.545 39.915 68.232 66.426 59.614 14.685-4.776 25.294-19.39 30.106-38.53 19.69 1.339 36.869-4.237 45.949-16.726 16.39-22.549 0.198-59.078-36.17-81.596z"/> <path d="m169.89 241.43c-7.338-5.54-50.442-14.573-87.124 8.136-36.366 22.519-52.56 59.047-36.171 81.598 9.08 12.488 26.258 18.063 45.948 16.726 4.813 19.142 15.424 33.756 30.107 38.53 26.511 8.618 56.248-18.069 66.425-59.614 10.264-41.908-11.65-80.111-19.185-85.376z"/> <path d="m77.225 232.52c43.024-3.188 72.586-35.834 75.267-44.628 3-8.692-1.728-52.477-34.662-80.347-32.653-27.628-72.398-31.741-88.78-9.187-9.073 12.495-9.066 30.555-1.708 48.868-16.717 10.491-27.337 25.099-27.342 40.54-3e-3 27.878 34.568 47.911 77.225 44.754z"/> <path d="m198.04 154.79c9.192 0.168 49.374-17.856 65.703-57.792 16.185-39.593 7.813-78.664-18.699-87.273-14.687-4.769-31.86 0.818-47.004 13.477-15.144-12.657-32.318-18.244-47.004-13.477-26.513 8.609-34.884 47.682-18.698 87.273 16.326 39.935 56.51 57.96 65.702 57.792z"/> <circle cx="198.04" cy="198.04" r="35"/></svg> </div>
Leaflet中调用示例
// 注册自定义图标 const customMarkerIcon = L.divIcon({ html: `<!-- 上面修改后的marker-pin完整HTML代码放此处 -->`, className: 'custom-marker-wrap', iconSize: [30, 42], iconAnchor: [15, 42] // 锚点对准标记最底部,保证点位准确 }); // 添加标记到地图 L.marker([目标纬度, 目标经度], {icon: customMarkerIcon}).addTo(map);
关键修改说明
- 调整伪元素层级为
z-index:0,保证SVG显示在白色圆形上层 - 给SVG添加
rotate(45deg)反向旋转,抵消父容器的旋转角度,保证图标正向显示 - 调整padding和SVG尺寸,适配内层圆形大小,避免显示溢出
内容的提问来源于stack exchange,提问作者Maik Lowrey
相关产品推荐
相关产品推荐

