Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Leaflet draw toolbar when user creates a shape and enable it when the shape is deleted

I would like to prevent a user from creating more than one shape on the map. For example if the user creates a polygon, then all shape icons on the toolbar should be disabled. When the user deletes the previously created shape, then icons on the toolbar should get enabled.

How can I do this? I tried removing the toolbar on the draw:created event and adding a new toolbar on draw:deleted event but it lead to errors (see attached screenshot).

Error screenshot

like image 875
codejunkie Avatar asked Oct 18 '22 02:10

codejunkie


1 Answers

Leaflet enables us to remove and add the toolbars with remove() and addTo() methods.

What you need to do is to create two toolbars. One is a default L.Control.Draw and the other one is without the 'draw' component:

self.drawControlFull = new L.Control.Draw();

self.drawControlEdit = new L.Control.Draw({
  edit: {
    featureGroup: editableLayers,
    edit: false
  },
  draw: false
});

map.addControl(drawControlFull);

Then you just listen to the draw:created and draw:deleted events and you add/remove them as needed:

map.on('draw:created', function(e) {
  var type = e.layerType,
    layer = e.layer;

    self.drawControlFull.remove();
    self.drawControlEdit.addTo(map);

  editableLayers.addLayer(layer);
});

map.on('draw:deleted', function (e) {
    self.drawControlEdit.remove();
    self.drawControlFull.addTo(map);
});

This solution maybe doesn't cover all the use cases but it's just an example. I have also created a jsFiddle for this so you can see how it works.

like image 77
Marko Letic Avatar answered Oct 21 '22 05:10

Marko Letic