繁体   English   中英

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

[英]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 实例,请尝试使用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>
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM