Events on react-leaflet v3

1.8k Views Asked by At

I just want to catch the click event on the map. I'm either finding examples for v2 which won't work on v3, or very clear examples that work on plain leaflet but not quite in REACT-leaflet. The documentation on react-leaflet does not explain the examples so I don't know what it's happening here, if someone could please explain, it'd mean a lot to me.

My questions are: 1- how to catch the click event on the map, not on a marker. And what's the explanation for this code: 2- what does "map.locate" do 3- and what is locationfound

The example obviously works, but since I don't understand how, I can't modify it to suit my needs. Is there a way to have the documentation updated and expanded? I'm really tired and frustrated with this. Please help. (Code is taken from https://react-leaflet.js.org/docs/example-events)

function LocationMarker() {
  const [position, setPosition] = useState(null)
  const map = useMapEvents({
    click() {
      map.locate()
    },
    locationfound(e) {
      setPosition(e.latlng)
      map.flyTo(e.latlng, map.getZoom())
    },
  })

  return position === null ? null : (
    <Marker position={position}>
      <Popup>You are here</Popup>
    </Marker>
  )
}

render(
  <MapContainer
    center={{ lat: 51.505, lng: -0.09 }}
    zoom={13}
    scrollWheelZoom={false}>
    <TileLayer
      attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
    />
    <LocationMarker />
  </MapContainer>,
)
1

There are 1 best solutions below

0
On BEST ANSWER

Okay since nobody was helping, I kept on reading for a couple more days, and I understood the following: 1- how to catch the click event on the map, not on a marker. You create a function that encapsulates your marker and returns it, within it you use the useMapEvents hooks, which takes a list of events as keys of an object:

useMapEvents({
    click() {
      ...
    },
    locationfound(e) {
    ...
    }
}

You can also do it as arrow functions such as the code shown here -> https://react-leaflet.js.org/docs/api-map

function MyComponent() {
  const map = useMapEvents({
    click: () => {
     ...
    },
    locationfound: (location) => {
      ...
    },
  })
  return null
} 

This one returns null because it's just used to capture the events, but you might as well return a marker.

2- what does "map.locate" do? It finds the location of the device it's running on, same as what "vanilla" leaflet does. See here: https://leafletjs.com/reference-1.7.1.html#map-locate

3- and what is locationfound? It is a "location event":

I think the documentation needs some work, I hope to understand this to a point where I can help write. Sadly we only find code samples with no explanation on what they do. Thank you.