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

Change Center position of React leaflet map

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

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

以下是我正在尝试做的事情:

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

showPosition = (position) => {
  this.setState({ UserCurrentPosition: [position.coords.latitude, position.coords.longitude] })
}

所以在我使用setState改变用户当前位置后,标记的位置得到更新,但是地图的位置没有,所以我想知道我是否做错了什么,或者怎么会这样完成了。

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

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

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