Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify when Leaflet Draw cancel button is clicked

Problem

I'm using leaflet draw for my application, and I have the 'remove' button active. The remove button has three options:

  1. Save
  2. Cancel
  3. Clear All

I want function foo() to be called if the user clicks Save, however, I want function bar() to be called should they click Cancel.

Live demo

Solution

I know this could be achieved by simply giving it an ID, and adding an event listener, but it's not as clean as I think it should be.

Ideal Solution

Leaflet draw its own methods for detecting when the buttons are pressed but it seems to me they only do it for one level higher. For example:

draw:deletestop The type of edit this is. One of: remove Triggered when the user has finished removing shapes (remove mode) and saves.

- Leaflet Docs

This allows me to call foo() after the user has selected any of the three options, rendering that they have simply finished dealing with the remove button interaction.

I cannot find a way in the docs to be able to listen for leaflet draw firing an event on the individual buttons being pressed.

like image 311
Ed Prince Avatar asked Aug 23 '17 12:08

Ed Prince


2 Answers

The handler for the cancel/disable function is stored as part of your L.Control.Draw instance. So, you you can modify the handler right after you instantiate your L.Control.Draw object:

var myDrawControl = new L.Control.Draw();

myDrawControl._toolbars.edit.disable =  function () {
  if (!this.enabled()) {
    /* If you need to do something right as the
       edit tool is enabled, do it here right
       before the return */
    return;
  }

  this._activeMode.handler.revertLayers();
  /* If you need to do something when the
     cancel button is pressed and the edits
     are reverted, do it here. */
  L.Toolbar.prototype.disable.call(this);
};

The source for the handler is here and while this works well, you will have to be careful with future versions of Leaflet.Draw that may change the handler's functionality.

like image 88
Sean Brewer Avatar answered Oct 31 '22 19:10

Sean Brewer


The newest version of Leaflet.draw 0.4.14 you can use

map.on('draw:toolbarclosed', function(){ //Add code here});

like image 2
mblais29 Avatar answered Oct 31 '22 18:10

mblais29