An example of using the 'react-leaflet' new useLeaflet() hook?
Asked Answered
G

2

6

I'm trying to get a reference to the leaflet object using the hook, so I can query the new map boundaries on different events (like Map.getBoundaries()). I'm pretty new to reac-leaflet, and this approach might be completely wrong, but this is what I've got for now...

What I'm trying to do is to get the map boundaries on each moveend event, if that's helpful...

Glacialist answered 28/7, 2019 at 10:55 Comment(0)
S
6

First of all, you can only use the hook in a component that's inside the Map element:

<Map>
  <YourComponent />
</Map

And then inside your component you can do something like:

const YourComponent = () => {
  const { map } = useLeaflet();
  const [bounds, setBounds] = React.useState({});

  React.useEffect(() => {
    const eventHandler = event => {
      setBounds(event.target.getBounds());
      doSomethingElse();
    }
    map.on("moveend", eventHandler);

    return () => {
      map.off("moveend", eventHandler); // Remove event handler to avoid creating multiple handlers
    }
  }, [setBounds, map]);

  return {
    // Use bounds for whatever you need
    <div>Lat: {bounds.lat}; long: {bounds.lng}</div>
  }
}
Splenitis answered 13/9, 2019 at 12:31 Comment(0)
B
1

Handler:

const onMoveEnd = (event) => {
 const bounds = event.target.getBounds()
 console.log(bounds)
}   
    // _northEast: LatLng {lat: 47.51470804161579, lng: 19.071493148803714}
    // _southWest: ...

Component:

<Map onmoveend={onMoveEnd}></Map>
Brachycephalic answered 4/8, 2019 at 19:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.