簡體   English   中英

變更中心 position 的 React leaflet map

[英]Change Center position of React leaflet map

所以我想做的是,在我得到用戶 lat 和 lng 之后,我想改變 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更改用戶當前的 position 后,標記的 position 得到更新,但地圖的 position 不,所以我想知道我做錯了什么,或者如何完成。

我相信中心屬性只是初始化 map。

You will need to call a map function like map.panTo(LatLng) or map.setView() when you update the state.

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

創建一個單獨的組件,如下所示:

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

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

因此,每當 lat 和 lng 發生變化時,map 就會自動居中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM