leafletleaflet.drawturfjs

Using the same Plug-in for multiple purposes in leaflet


I am trying to use the leaflet-draw tool for two different things:

  1. as a "regular" tool to create new geometries
  2. if I draw a line, I perform some calculations with turf.js, giving me points nearby.

I've set up two individual draw controls for each purpose. For the second, I have all but the draw:polyline disabled. The problem: I save my elements with the

map.on('draw:created', function(){...});

"command". But this way I (or the eventhandler, respectively :)) cant differentiate, if the line was drawn with the first or the second button. So basically i can use the draw tool either for one thing or the other. Is there a way where I can use the same tool for different applications on the same map?

Thanks for any hints or work arounds.


Solution

  • An alternative would be to use Leaflet-Geoman instead of Leaflet-Draw.

    There you can create copies of Draw instances and add them a new shape name:

    // copy a rectangle and customize its name, block, title and actions
    map.pm.Toolbar.copyDrawControl('Polygon', {
      name: 'PolygonCopy',
      block: 'custom',
      title: 'Display text on hover button',
      actions: ['cancel', 'removeLastVertex', 'finish'],
    });
    

    And then you can check the shape name in the create event:

    // listen to when a new layer is created
    map.on('pm:create', function(e) {
      console.log(e)
      if(e.shape === 'Polygon'){
        alert('Original Polygon')
      }else if(e.shape === 'PolygonCopy'){
        alert('Copy Polygon')
      }
    });
    

    https://jsfiddle.net/falkedesign/r0sm9auo/