Search code examples
javascriptreactjsleafletreact-leaflet

The Center in a MapContainer in React-Leaflet-js Won't Update


I've started to use React.js lately and was working on a project using React-Leaflet-js. My problem is that my MapContainer doesn't change the center of the page whenever the position variable in the following code is updated:

...
  render() {
    const position = [this.state.location.lat, this.state.location.lng];
    return (
      <MapContainer
      className="map"
      center={position}
      zoom={this.state.zoom}
      scrollWheelZoom={true}>
...

For reference, the state variable that is being updated looks like this:

    state = {
    location: {
      lat: 40.7128,
      lng: -74.0060,
    },
    haveUsersLocation: false,
    zoom: 13,
  }

What's weird is that a marker with a position set to {position} will automatically update when the position variable changes but not the center of the MapContainer. I'm not sure why the map doesn't respond and adjust its center.

Note: I tried looking at this but it didn't answer my question. Please help.


Solution

  • The center property just initializes the map, if you want to update the center of the map actually shown you have to use either setView or flyTo if you want a smooth animation. In order to get a Leaflet Map reference you need to use the hook useMap.

    function FlyMapTo() {
    
        const map = useMap()
    
        useEffect(() => {
            map.flyTo(position)
        }, [position])
    
        return null
    }
    
    return (
    <MapContainer
          className="map"
          center={position}
          zoom={this.state.zoom}
          scrollWheelZoom={true}>
        <FlyMapTo />
    </MapContainer>
    )