谷歌地图marker自定义svg图标,使用本地图片方法

本文介绍如何在Google Maps中使用自定义SVG图标创建标记,并通过AdvancedMarkerElement实现更高效的图标渲染。探讨了不同方法的优缺点,包括直接使用SVG路径、组合多个图标以及使用在线资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// create svg url with fill color
const markerSvg = window.btoa(`
    <svg width="32" height="39" viewBox="0 0 32 39" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M16 0C7.1648 0 0 7.032 0 15.704C0 24.512 7 30.5328 16 38.4C25 30.5328 32 24.512 32 15.704C32 7.032 24.8352 0 16 0Z" fill="#0063CC"/>
<circle cx="16" cy="17" r="8" fill="white"/>
</svg>
`);

const marker = new google.maps.Marker({
        position: {
          lat: ele.Coordinate.Latitude,
          lng: ele.Coordinate.Longitude,
        },
        map: datas.map,
        title: String(ele.Id),
        icon: {
          url: `data:image/svg+xml;base64,${markerSvg}`, //most point
          scaledSize: new google.maps.Size(32, 39),
        },
      });

找了一圈官网是要自定义svg的path,但是图标是两个path的svg,刚开始使用combine marker,效果有点卡,而且在聚合的时候两个marker没有combine成功,要么使用线上路径

最后,在查看cluster的部分找到示例Compare clustering renderers

-------24年更新------

marker官方建议替换为AdvancedMarkerElement

一个栗子:

  // create svg url with fill color
  const markerSvgString = `
      <svg width="32" height="39" viewBox="0 0 32 39" fill="none" xmlns="http://www.w3.org/2000/svg">
  <path d="M16 0C7.1648 0 0 7.032 0 15.704C0 24.512 7 30.5328 16 38.4C25 30.5328 32 24.512 32 15.704C32 7.032 24.8352 0 16 0Z" fill="#0063CC"/>
  <circle cx="16" cy="17" r="8" fill="white"/>
  </svg>
  `;
 
 function buildContent(icon = markerSvgString, label: unknown = '') {
    // A marker with a custom SVG glyph.
    const content = document.createElement('div');
    content.innerHTML = label
      ? `<div style="position:relative; margin-top:4px; text-align:center">${icon}
    <div style="position:absolute; width:100%; top:7px; display:flex; justify-content:center"><span style="color:#ffffff; font-weight:bold;font-size:16px">${label}</span></div>
    </div>`
      : `<div style="position: relative;margin-top:4px">${icon}</div>`;
    return content;
  }

const marker = new google.maps.marker.AdvancedMarkerElement({
        position: {
          lat: ele.coordinate.latitude,
          lng: ele.coordinate.longitude,
        },
        map: mapSelf,
        title: String(ele.name),
        content: buildContent(),
        zIndex: 1,
      });

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值