Leaflet catch fitBounds event, but not moveend

Viewed 198

Is it possible to catch only fitBounds event, but not moveend event?

1 Answers

There is no Leaflet built-in event dedicated to the fitBounds method. But since this method is called imperatively, you can easily execute whatever code you want alongside it.

map.fitBounds(myBounds);
// some code related to fitBounds
// e.g. you can trigger your own event:
map.fire("fitbounds-custom-event");

What may be implied by your question, is to detect the end of the potential fitBounds animation, as opposed to the end of user-initiated navigation (user pan, zoom...). Unfortunately there is currently nothing built in Leaflet either for this feature, although it has been discussed for a while (see Leaflet/Leaflet #2934).

One difficulty is that you can start a programmatic fitBounds with animation, and even though that animation is quite fast, user can navigate in the middle, ending the movement prematurely and in a different position. In that case, is it still considered the end of the fitBounds animation, or end of the user navigation?

If we ignore this difficulty, then a possible solution could be to attach a one time event listener when calling fitBounds:

map.once("moveend zoomend", myCallback);
map.fitBounds(myBounds);
Related