我正在使用 Google ReactJS 库将地图添加到我的 React Web 应用程序中,并使用 @googlemaps/react-wrapper 库来集群标记。但我无法在包装器上进行标记聚类。如果有人有任何想法,请帮助解决问题。
组件代码如下:
import React, { useEffect, useRef } from "react";
import { Wrapper, Status } from "@googlemaps/react-wrapper";
export default function MapContainer({ center, zoomLevel, markerList, icon }) {
const googleMapRef = useRef(null);
let googleMap = null;
useEffect(() => {
try {
let bounds = new window.google.maps.LatLngBounds();
const initGoogleMap = () => {
return new window.google.maps.Map(googleMapRef.current, {
center: center,
zoom: zoomLevel,
styles: [{ stylers: [{ saturation: -100 }] }]
});
}
const createMarker = (markerObj) => new window.google.maps.Marker({
position: { lat: parseFloat(markerObj.lat), lng: parseFloat(markerObj.lng) },
map: googleMap,
icon: {
url: icon,
scaledSize: new window.google.maps.Size(80, 80)
},
});
googleMap = initGoogleMap();
markerList.map(x => {
const marker = createMarker(x);
bounds.extend(marker.position);
});
if (markerList.length === 0) {
initGoogleMap();
bounds = new window.google.maps.LatLngBounds();
}
googleMap.fitBounds(bounds);
}
catch (e) {
console.log("maps", e)
}
})
const render = (status) => {
if (status === Status.LOADING) return "Loading...";
if (status === Status.FAILURE) return "Error";
return null;
};
return (
<div>
<div>
<Wrapper apiKey={TOKEN} render={render}>
{/* <GISTrackingMap zoomLevel={props.zoomLevel} mapFilterByVal={props.mapFilterByVal} center={props.center} gisTrackingData={props.gisTrackingData} /> */}
<div ref={googleMapRef} style={{ width: "100%", height: "78vh" }} />
</Wrapper>
</div>
</div>
)
}
要创建聚类器,您必须有一组标记。所以我建议搬家bounds.extend(marker.position);
脱离markerList映射并保存结果:
const markers = markerList.map(x => {
createMarker(x);
});
然后创建一个集群器:
new MarkerClusterer({ googleMapRef, markers });
UPD看起来 MarkerClusterer 不适用于ref
,所以上面的代码应该修改如下:
new MarkerClusterer({ googleMap, markers });
不要忘记安装库并添加导入:
yarn add @googlemaps/markerclusterer
import { MarkerClusterer } from '@googlemaps/markerclusterer';
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)