更改React传单地图的中心位置

the*_*her 6 javascript leaflet reactjs react-leaflet

所以我想做的是,我想在获得用户的纬度和经度后更改地图的中心,下面的代码将使问题更清楚:

<LeafletMap
  center={this.state.UserCurrentPosition}
  zoom={17}
  maxZoom={20}
  attributionControl={true}
  zoomControl={false}
  doubleClickZoom={true}
  scrollWheelZoom={true}
  dragging={true}
  animate={true}
  easeLinearity={0.35}
>
  <TileLayer url='https://tiles.stadiamaps.com/tiles/alidade_smooth_dark/{z}/{x}/{y}{r}.png'/>
  <Marker 
    position={this.state.UserCurrentPosition} 
    icon={L.divIcon({
      className: 'user-marker',
      html: `<div  class='icon icon-location'><span class="circle"></span></div>`,
      iconSize: [40, 40],
      iconAnchor: [24, 24]
    })}>
  </Marker>
</LeafletMap>
Run Code Online (Sandbox Code Playgroud)

以下是我想要做的:

componentDidMount() {
  navigator.geolocation.getCurrentPosition(this.showPosition);
}

showPosition = (position) => {
  this.setState({ UserCurrentPosition: [position.coords.latitude, position.coords.longitude] })
}
Run Code Online (Sandbox Code Playgroud)

因此,在我使用setState更改用户的当前位置后,标记的位置会更新,但地图的位置不会更新,所以我想知道我是否做错了什么,或者如何完成。

小智 9

创建一个单独的组件,如下所示:

const RecenterAutomatically = ({lat,lng}) => {
 const map = useMap();
  useEffect(() => {
    map.setView([lat, lng]);
  }, [lat, lng]);
  return null;
}
Run Code Online (Sandbox Code Playgroud)

在 MapContainer 内调用此组件

<MapContainer center={[lat, lon]} zoom={80} scrollWheelZoom={true}>
        <TileLayer
          attribution='<a href="https://www.openstreetmap.org/copyright"></a>'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        <Marker position={[lat,lng]}></Marker>
        <RecenterAutomatically lat={lat} lng={lng} />
</MapContainer>
Run Code Online (Sandbox Code Playgroud)

因此,每当纬度和经度发生变化时,地图就会自动居中。


dou*_*ald 8

我相信中心属性只是初始化地图。

当您更新状态时,您将需要调用地图函数,例如map.panTo(LatLng)或。map.setView()

useMap()您可以按照此示例使用挂钩https://react-leaflet.js.org/docs/example-animated-panning