Change Center position of React leaflet map
Asked Answered
F

2

7

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.

Furbish answered 16/12, 2020 at 11:47 Comment(0)
D
9

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

Drab answered 16/12, 2020 at 11:53 Comment(3)
in order to do that, i should change my component to functional, and considering what i have done with it, it's a lot of work, is there another way for it maybe?Furbish
I think the alternative is to set and then get a ref to your map and then use that within showPosition() to call map.setView() etcDrab
It's worth mentioning that the useMap hook is accessible in a "descendant" component of a MapContainer and NOT outside of it. This is also correct for useMapEvents and useMapEvent hooks. see docs at react-leaflet.js.org/docs/api-map/#usemapDwyer
M
11

Create a separate component as given below:

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

Invoke this component inside 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>

So whenever lat and lng changes, the map recenters automatically..

Mackle answered 11/8, 2022 at 8:51 Comment(0)
D
9

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

Drab answered 16/12, 2020 at 11:53 Comment(3)
in order to do that, i should change my component to functional, and considering what i have done with it, it's a lot of work, is there another way for it maybe?Furbish
I think the alternative is to set and then get a ref to your map and then use that within showPosition() to call map.setView() etcDrab
It's worth mentioning that the useMap hook is accessible in a "descendant" component of a MapContainer and NOT outside of it. This is also correct for useMapEvents and useMapEvent hooks. see docs at react-leaflet.js.org/docs/api-map/#usemapDwyer

© 2022 - 2024 — McMap. All rights reserved.