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

如何将Google Map的Marker Clusterer升级至@googlemaps/markerclusterer?

升级Google Maps Marker Clusterer到@googlemaps/markerclusterer步骤

1. 移除旧的弃用脚本

先删掉原来引入旧版Marker Clusterer的代码:

<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>

2. 引入新版库

有两种方式可选:

  • CDN引入(适合纯前端项目)
    使用ES模块方式引入,要放在Google Maps API脚本之后:
    <script async src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>
    <script type="module">
      import { MarkerClusterer } from 'https://unpkg.com/@googlemaps/markerclusterer/dist/index.esm.js';
      // 后续初始化代码写在这里
    </script>
    
  • npm安装(适合构建类项目)
    先安装依赖:
    npm install @googlemaps/markerclusterer
    
    然后在代码中导入:
    import { MarkerClusterer } from '@googlemaps/markerclusterer';
    

3. 修改Marker Clusterer初始化代码

旧版的初始化逻辑和新版略有不同,以下是示例对比:

  • 旧版弃用代码
    function initMap() {
      const map = new google.maps.Map(document.getElementById('map'), {
        zoom: 3,
        center: { lat: -28.024, lng: 140.887 }
      });
      const markers = [/* 你的标记数组 */];
      new MarkerClusterer(map, markers, {
        imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
      });
    }
    
  • 新版代码
    function initMap() {
      const map = new google.maps.Map(document.getElementById('map'), {
        zoom: 3,
        center: { lat: -28.024, lng: 140.887 }
      });
      const markers = [/* 你的标记数组 */];
      
      // 初始化新版MarkerClusterer
      new MarkerClusterer({ map, markers });
      
      // 可选:自定义聚类样式
      // new MarkerClusterer({
      //   map,
      //   markers,
      //   renderer: {
      //     render: ({ count, position }) => {
      //       return new google.maps.Marker({
      //         label: { text: String(count), color: 'white', fontSize: '12px' },
      //         position,
      //         // 自定义图标等样式
      //         icon: {
      //           url: 'path/to/your/cluster-icon.png',
      //           scaledSize: new google.maps.Size(40, 40)
      //         }
      //       });
      //     }
      //   }
      // });
    }
    

注意事项

  • 新版库采用ES模块规范,现代浏览器原生支持,若需兼容旧浏览器可通过打包工具转译
  • 自定义聚类样式的方式和旧版不同,新版通过renderer选项实现,灵活性更高
  • 确保Google Maps JavaScript API已正确加载,API密钥配置无误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 16:22:12