Enable / disable control when zooming

936 views
Skip to first unread message

Ben

unread,
Feb 11, 2013, 6:19:28 AM2/11/13
to leafl...@googlegroups.com
I have a draw tool that I would enable when zoomed in => zoom level 6, and disabel when zooming < zoom level 6. 

I have set up a function do to this:

    // add draw tool based on zoom level
    map.on('zoomend', onZoomend);
    function onZoomend() {
        if(map.getZoom() >= 6)
            map.addControl(drawControl);

        if (map.getZoom() < 6)
            map.removeControl(drawControl);
    }; 

However, the function will continue to add multiple draw tool controls as one continues to zoom in.
What is the correct way of doing this?
Cheers,
Ben

Dave Martin

unread,
Feb 11, 2013, 7:06:49 AM2/11/13
to leafl...@googlegroups.com


On Monday, 11 February 2013 11:19:28 UTC, Ben wrote:
I have a draw tool that I would enable when zoomed in => zoom level 6, and disabel when zooming < zoom level 6. 
......
However, the function will continue to add multiple draw tool controls as one continues to zoom in.


Ben,

I can't see any easy way to query if the control is already present, so on a generic basis my suggestion would be to maintain your own stateful information, either as a global variable or persisted as an invisible element on your page. 

When you first create the page, assuming its zoomed-out, set the variable to "draw_control_state = off".  Then, whenever your zoomend would detects the draw control should be present, check your state variable and if "draw_control_state = off" then add the control and set "draw_control_state = on"; if it is already "draw_control_state = on" then just skip as no redraw needed.  Going the other way, just remove the control and ensure "draw_control_state = off" (you could optimise speed when zooming out by only removing if "draw_control_state = on").

Dave

Dave Martin

unread,
Feb 11, 2013, 7:23:51 AM2/11/13
to leafl...@googlegroups.com


On Monday, 11 February 2013 12:06:49 UTC, Dave Martin wrote:

I can't see any easy way to query if the control is already present,.....
Dave

Ben - another idea has just occurred to me. Although there's no overt call to check if a control is present, depending on how the draw control is implemented, if it extends the standard Leaflet control architecture, maybe you could use the results (or lack thereof) from polling getPosition ?   http://leafletjs.com/reference.html#control

Dave

Ben

unread,
Feb 11, 2013, 8:29:26 AM2/11/13
to leafl...@googlegroups.com
Hi Dave, thanks for the help, I found a solution:

    function onZoomend() {
        
        try { 
            map.removeControl(drawControl); 
        } 
        catch (err){ 
            console.log('no draw control to remove'); 
        };

        if (map.getZoom() > 6) {
            map.addControl(drawControl);
        };

    };
    map.on('zoomend', onZoomend);

Ben
Reply all
Reply to author
Forward
Message has been deleted
0 new messages