[英]How to change center Latitude and Longitude of a mapbox-gl in react js?
我正在為 Mapbox 使用 Mapbox-gl package。 我在 useEffect 中渲染 map,我想做的是更改 Mapbox 的中心,而不完全重新渲染 map。 例如
const mapContainerRef = useRef(null);
const [markerLngLat, setMarkerLngLat] = useState([85.324, 27.7172]);
useEffect(() => {
const map = new mapboxgl.Map({
container: mapContainerRef.current,
style: 'mapbox://styles/lmaps/ckl6t1boq578819qod5v7ynby',
center: markerLngLat,
zoom: 13,
});
},[]);
return (
<div>
<a onClick={setMarkerLngLat([65.468754, 44.57875])} />
<div className='listing-map-container' ref={mapContainerRef}></div>
</div>
);
通過單擊按鈕,我想將 map 的中心從以前的 lat long 移動到新設置的 Latlong 而不重新渲染整個 map。 在 useEffect 的 [] 中傳遞 markerLngLat 有效,但它完全重新渲染 map 和它上面的所有其他 1000 個標記,所以不能更喜歡這種方式。 實際代碼要長得多,並且 map 上標記了許多標記,所以我不想完全重新渲染 map。
每次設置新的 state 時,您都在重新創建 Mapbox 實例,請嘗試使用setCenter
或flyTo
之類的方法,直接到該實例,例如:
const mapRef = useRef();
const [mapObject, setMap] = useState();
useEffect(() => {
const map = new mapboxgl.Map({
container: mapContainerRef.current,
style: 'mapbox://styles/lmaps/ckl6t1boq578819qod5v7ynby',
center: markerLngLat,
zoom: 13,
});
setMap(map);
},[]);
function setMapCenter(coords) {
if (mapObject) {
mapObject.setCenter(coords);
}
}
return (
<div>
<a onClick={() => setMapCenter([65.468754, 44.57875])} />
<div className='listing-map-container' ref={mapRef}></div>
</div>
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.