43

So I'm making this application with leafet.js.

This application requires that I have to manually draw grids onto the screen, that I've taken care in a draw_grid() function that draws a bunch of polygons to the screen.

I have this function that I'm calling to trigger the change of the leaflet map.

zoom - the zoom integer and size is a dict like {x:1,y:1} that controls the size of the tiles drawn onto the map. (they need to change as the units the tiles are being drawn under are lat,long points on the map.

function changeZoom(zoom,size){
    map.setZoom(zoom); 
    setSize(size);   
    setTimeout(drawGrid,500)s;
}

The reason I have to use the setTimeout is because the leaflet ignores any drawing commands onto the map (which I'm doing as a layer) until the map has finished animating.

How to do this asynchronously instead?

3 Answers 3

71

You can use the map.zoomend event, described in the API here

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

Once the map finishes the zooming animation, it will then call the drawGrid function.

3
  • 3
    This event still seems to fire for me many times during a "scroll-in zoom". Is it because I'm using a touchpad? Commented Sep 3, 2014 at 1:47
  • 1
    is there a way to check for multiple events like "paning" as well as "zooming" ? also i checked that "load" event is not getting fired.
    – ram
    Commented Jun 24, 2015 at 7:25
  • @SamSelikoff seems not to be related to touchpad. Also happens by mousewheel, if not scrolled supersuperfast. Couldn't find any debounce option either. Thus, thus logic needs to be implemented manually.
    – phil294
    Commented Mar 26, 2017 at 2:16
19

In newer version of Leaflet, "zoomed" is no longer an event. There are now "zoomstart" and "zoomend" events:

map.on("zoomstart", function (e) { console.log("ZOOMSTART", e); });
map.on("zoomend", function (e) { console.log("ZOOMEND", e); });
2

This is best way to managed Leaflet Zoom control clicked

    /*Zoom Control Click Managed*/
    var bZoomControlClick = false;
    mymap.on('zoomend',function(e){
        var currZoom = mymap.getZoom();
        if(bZoomControlClick){
            console.log("Clicked "+currZoom);
        }
        bZoomControlClick = false;
    });     
    var element = document.querySelector('a.leaflet-control-zoom-in');
    L.DomEvent.addListener(element, 'click', function (e) {
        bZoomControlClick = true;
        $(mymap).trigger("zoomend");
    });
    var element1 = document.querySelector('a.leaflet-control-zoom-out');
    L.DomEvent.addListener(element1, 'click', function (e) {
        bZoomControlClick = true;
        $(mymap).trigger("zoomend");
    });

Not the answer you're looking for? Browse other questions tagged or ask your own question.