3

我正在为 Mapbox 使用 Mapbox-gl 包。我在 useEffect 中渲染地图,我想要做的是更改 Mapbox 的中心而不完全重新渲染地图。例如

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>
);

通过单击按钮,我想将地图的中心从以前的 lat long 移动到新设置的 Latlong 而不重新渲染整个地图。在 useEffect 的 [] 中传递 markerLngLat 有效,但它会完全重新渲染地图和其上的所有其他 1000 个标记,因此不能更喜欢这种方式。实际代码要长得多,并且地图上标记了许多标记,所以我不想完全重新渲染地图。

4

1 回答 1

4

每次设置新状态时,您都在重新创建 Mapbox 实例,请尝试使用某种方法,例如setCenteror 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>
);
于 2021-03-05T22:40:20.050 回答