user8072194
user8072194

Reputation:

Can you turn Leaflet EasyButton off automatically on 'mouseup'?

I would like to have the user be able to turn on a state changing EasyButton, select an area on the map (by holding down the shift key and dragging the mouse), and then once the mouse is released, have the easy button turned off automatically. Right now, you turn the easybutton on, select an area which gives you Lat/Long for a bounding box. Works great. BUT, when you click to turn the EasyButton off, it overrides your selection (assigns new coordinates to the area you clicked where the EasyButton is). My code:

    var stateChangingButton = L.easyButton({
            states: [{
                    stateName: 'ButtonOff',      
                    icon:      'X',               
                    title:     'Turn Button On', 
                    onClick: function(btn, map) {    
                            btn.button.style.backgroundColor = 'red';
                            btn.state('ButtonOn');
                            map.on('mousedown', getClickLocation);
                            map.on('mouseup', getReleaseLocation);
                            map.on('mouseup', toGeoJsonBounds);
                            map.on('mouseup', addSelectionLayer);
                            map.on('mouseup', addColorSelection);                                
                    }
                }, {
                    stateName: 'ButtonOn',
                    icon:      'X',
                    title:     'Turn Button Off',
                    onClick: function(btn, map) {
                        btn.state('ButtonOff');
                            btn.state('ButtonOff');
                            btn.button.style.backgroundColor = 'white';
                            map.off('mousedown', getClickLocation);
                            map.off('mouseup', getReleaseLocation);
                            map.off('mouseup', toGeoJsonBounds);
                            map.off('mouseup', addSelectionLayer);
                            map.off('mouseup', addColorSelection);                             

                    }
                    }]
                });

                stateChangingButton.addTo(map);

I have tried this in a desperate attempt and it gives an error:

       //map.on('mouseup', btn.state('ButtonOff')); 

I have tried creating a function and it says btn is undefined:

        function buttonAutoOff(){
            btn.state('ButtonOff');
         }

I'm new to JavaScript and Leaflet and I have to do this for my job. Is what I'm asking even possible?

Thank you!

Upvotes: 1

Views: 459

Answers (1)

andrea689
andrea689

Reputation: 674

You should use "boxzoomend" event.

map.on('boxzoomend', function(){
  stateChangingButton.state('ButtonOff');
  stateChangingButton.button.style.backgroundColor = 'white';
}); 

jsfiddle example: https://jsfiddle.net/andrea689/y0xpmpm0/

Upvotes: 1

Related Questions