如何在react js中更改mapbox-gl的中心纬度和经度?

Ank*_*hah 4 javascript mapbox reactjs mapbox-gl mapbox-gl-js

我正在为 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>
);
Run Code Online (Sandbox Code Playgroud)

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

Adr*_*lid 5

每次设置新状态时,您都会重新创建 Mapbox 实例,请尝试使用某种方法,例如setCenterflyTo,直接到实例,例如:

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>
);
Run Code Online (Sandbox Code Playgroud)