如何将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/markerclustererimport { 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
相关产品推荐
相关产品推荐

