Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在react js中更改地图框gl的中心纬度和经度?_Javascript_Reactjs_Mapbox_Mapbox Gl Js_Mapbox Gl - Fatal编程技术网

Javascript 如何在react js中更改地图框gl的中心纬度和经度?

Javascript 如何在react js中更改地图框gl的中心纬度和经度?,javascript,reactjs,mapbox,mapbox-gl-js,mapbox-gl,Javascript,Reactjs,Mapbox,Mapbox Gl Js,Mapbox Gl,我正在使用Mapbox gl包来创建Mapbox。我在useEffect中渲染贴图,我要做的是更改Mapbox的中心,而不完全重新渲染贴图。 比如说 const mapContainerRef = useRef(null); const [markerLngLat, setMarkerLngLat] = useState([85.324, 27.7172]); useEffect(() => { const map = new mapboxgl.Map({

我正在使用Mapbox gl包来创建Mapbox。我在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>
</div>
);
const-mapContainerRef=useRef(null);
const[markerLngLat,setMarkerLngLat]=useState([85.324,27.7172]);
useffect(()=>{
常量映射=新的mapboxgl.map({
容器:mapContainerRef.current,
风格:'mapbox://styles/lmaps/ckl6t1boq578819qod5v7ynby',
中心:Markerlinglat,
缩放:13,
});
},[]);
返回(
);
单击按钮,我想将地图的中心从上一个lat long移动到新设置的Latlong,而不重新渲染整个地图。 在[]in useffect中传递markerLngLat是可行的,但它会完全重新渲染地图和地图上的所有其他1000个标记,因此不能选择这种方式。
实际代码要长得多,地图上标记了许多标记,因此我不想完全重新渲染地图。

如果您每次设置新状态时都要重新创建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>
);
const mapRef=useRef();
常量[mapObject,setMap]=useState();
useffect(()=>{
常量映射=新的mapboxgl.map({
容器:mapContainerRef.current,
风格:'mapbox://styles/lmaps/ckl6t1boq578819qod5v7ynby',
中心:Markerlinglat,
缩放:13,
});
setMap(map);
},[]);
函数setMapCenter(coords){
如果(映射对象){
mapObject.setCenter(coords);
}
}
返回(
setMapCenter([65.468754,44.57875])}/>
);