Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to place on-load event handler with React Leaflet?

I need help on react-leaflet for my map-based app. I am trying to add an on-load function where a function would execute on load once the client logged onto the map. But on react-leaflet, there is no onLoad.

Right now I simply have this:

function CenterCoords() {
    const map = useMapEvents({
        // TODO resolve onload
        layeradd() {
            map.locate()
            console.log('loading')
        },
        locationfound(e: any) {
            map.flyTo(e.latlng, map.getZoom())
        },
    })
    return null
}

I only used layeradd but I have no idea what that means and react-leaflet documentation offers no hint on its leaflet handler function. And if I rely on leaflet documentation, load and loading do not seem to work.

like image 208
Beaumont Avatar asked Dec 08 '25 14:12

Beaumont


1 Answers

The MapContainer component takes a whenReady prop, which is a function that fires when the map is ready. It also takes a whenCreated prop, which is a function of the underlying leaflet L.map instance. But you can do whatever you want with it:

<MapContainer
  center={center}
  zoom={zoom}
  scrollWheelZoom={false}
  whenReady={() => {
    console.log("This function will fire once the map is created")
  }}
  whenCreated={(map) => {
    console.log("The underlying leaflet map instance:", map)
  }}>
    ...
</MapContainer>

load and loading events are more specific to layers, like tileLayers or imageLayers.

like image 75
Seth Lutske Avatar answered Dec 10 '25 04:12

Seth Lutske



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!