Search code examples
javascriptreactjsleafletreact-leaflet

Change Center position of React leaflet map


So what I'm trying to do is, I want to change the center of map after I get the users lat and lng, the code below will make the problem clearer:

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

and below is what I'm trying to do:

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

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

So after I use setState to change the user's current position, the marker's position gets updated, but the map's position no, so I was wondering if i'm doing something wrong, or how can it be accomplished.


Solution

  • I believe the center property is only to initialise the map.

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

    You can use the useMap() hook as per this example https://react-leaflet.js.org/docs/example-animated-panning