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...
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.
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>
}
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With