Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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...

like image 439
bitstream Avatar asked Jul 28 '19 10:07

bitstream


People also ask

Is react leaflet good?

Leaflet and its React counterpart, React Leaflet, are a fantastic open source and free mapping alternative to Google Maps and MapBox, no API key required! It is an easy package to work with and one worth trying out.


2 Answers

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>
  }
}
like image 103
vobango Avatar answered Oct 29 '22 19:10

vobango


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>
like image 29
bmz1 Avatar answered Oct 29 '22 20:10

bmz1