Skip to content

moveend event fired many times when page is load with Leaflet

I need to do some operations when the map is paned or zoomed, so I attached a callback to the event moveend.

map.on('moveend', function() {
    // code stuff
});

It works fine, but when the page is load the event is fired three times and I don’t know why. Probably because during its creation the map is moved.

To avoid this i tried to wait the load event before subscribing moveend event, but nothing changed. So I tried to attach it within whenReady callaback, but again it is fired three times.

map.whenReady(function() {
    map.on('moveend', function() {
        // code stuff
    });
});

Finally, I discovered that after the resize event it works quite fine: moveend is fired jonly one time. But I really believe there is a best way to fix the problem.

Another solution could be to attach my callback to both events zoomend and dragend, to cover paning and zooming cases. But I didn’t find a way to do it.

Thank you for your help.

Answer

The best solution I found is to attach the callback to both events:

    map.on('zoomend', function() {
        // callback
    });

    map.on('dragend', function() {
        // callback
    });

Although this way the code is a bit replicated, this is by far the best solution.