@react-google-maps/api的MarkerClusterer组件标记不显示求助
解决@react-google-maps/api MarkerClusterer标记不显示问题
几个关键问题及修复方案:
组件导入路径错误
你代码里用require('../../')导入组件,大概率是路径配置错误,应该直接从@react-google-maps/api包导入,确保组件能正确加载。替换自定义ScriptLoaded为官方LoadScript
自定义的ScriptLoaded可能没正确处理Google Maps脚本的加载状态,改用官方提供的LoadScript组件,同时传入你的API密钥才能正常加载地图资源。重复位置的Key冲突
当多个标记位置完全相同时,createKey返回的lat+lng会重复,React无法区分这些组件,导致渲染异常。需要给每个标记生成唯一Key,比如结合索引和坐标值。MarkerClusterer的imagePath资源可访问性
你使用的Google官方示例图片路径可能存在跨域或访问限制,建议换成本地资源或者确保路径下的m1.png到m6.png文件都存在,若不需要自定义集群图标,可直接去掉options配置。
修复后的完整代码:
import { GoogleMap, LoadScript, MarkerClusterer, Marker } from '@react-google-maps/api'; const mapContainerStyle = { height: '400px', width: '800px', }; const center = { lat: -28.024, lng: 140.887 }; const locations = [ { lat: -31.56391, lng: 147.154312 }, { lat: -33.718234, lng: 150.363181 }, { lat: -33.727111, lng: 150.371124 }, { lat: -33.848588, lng: 151.209834 }, { lat: -33.851702, lng: 151.216968 }, { lat: -34.671264, lng: 150.863657 }, { lat: -35.304724, lng: 148.662905 }, { lat: -36.817685, lng: 175.699196 }, { lat: -36.828611, lng: 175.790222 }, { lat: -37.75, lng: 145.116667 }, { lat: -37.759859, lng: 145.128708 }, { lat: -37.765015, lng: 145.133858 }, { lat: -37.770104, lng: 145.143299 }, { lat: -37.7737, lng: 145.145187 }, { lat: -37.774785, lng: 145.137978 }, { lat: -37.819616, lng: 144.968119 }, { lat: -38.330766, lng: 144.695692 }, { lat: -39.927193, lng: 175.053218 }, { lat: -41.330162, lng: 174.865694 }, { lat: -42.734358, lng: 147.439506 }, { lat: -42.734358, lng: 147.501315 }, { lat: -42.735258, lng: 147.438 }, { lat: -43.999792, lng: 170.463352 }, ]; // 自定义集群图标配置,不需要可删除 const clusterOptions = { imagePath: '/your-local-cluster-icons/m', // 替换为你自己的图标路径,确保m1-m6.png存在 }; const MapWithMarkerClusterer = () => { return ( <LoadScript googleMapsApiKey="YOUR_GOOGLE_MAPS_API_KEY"> {/* 替换为你的API密钥 */} <GoogleMap id='marker-example' mapContainerStyle={mapContainerStyle} zoom={3} center={center} > <MarkerClusterer options={clusterOptions}> {(clusterer) => locations.map((location, index) => ( {/* 用索引+坐标生成唯一Key,解决重复位置的Key冲突 */} <Marker key={`${location.lat}-${location.lng}-${index}`} position={location} clusterer={clusterer} /> )) } </MarkerClusterer> </GoogleMap> </LoadScript> ); }; export default MapWithMarkerClusterer;
额外注意事项:
- 必须将
YOUR_GOOGLE_MAPS_API_KEY替换为你自己的Google Maps API密钥,且确保密钥已启用Maps JavaScript API。 - 检查地图容器的样式是否生效,确保容器有明确的宽高,否则地图可能无法正常显示。
内容的提问来源于stack exchange,提问作者kacper3671
相关产品推荐
相关产品推荐

