22

I am using leaflet to develop a new application. You can have an idea of the app here.

I would like to fire an event whenever the bounds of the map change. I looked at the doc but couldn't find anything related to that.

I have found the getBounds() method, and the list of possible event methods, but nothing combining both.

The only other possibility I see to do that is to check for mouse drag and scroll events and check the bounds every time. But I was hoping there would be something better to do.

Would you have a better idea? Thanks!

jlengrand
  • 12,152
  • 14
  • 57
  • 87

2 Answers2

48

Map bounds are updated each time the map is moved (either by pan or zoom). So you can use moveend event for your purpose

map.on('moveend', function(e) {
   var bounds = map.getBounds();
});
YaFred
  • 9,698
  • 3
  • 28
  • 40
2

On react-leaflet, when setting maxBounds directly on the MapContainer component from leaflet, I had a warning listener not found at MapContainer with a stack trace.

If anybody runs on this issue from react-leaflet, I found a work around like this :

function MapEventHandlers() {
  const mapMoveEnd = useMapEvent('moveend', () => {
    mapMoveEnd.setMaxBounds([
      [51.234567, -5.67],
      [41.234567, 10.69],
    ])
  })
}

(...)

<MapContainer (...) >
  <MapEventHandlers />
  <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
  (...)
</MapContainer>

Hope it helps :)

Clovis
  • 21
  • 1