leafletleaflet-drawleaflet-geoman

Limit maker points in Polyline (to be a Line) using leaflet-geoman


I want to enable the user to draw a Line (which is a Polyline with only 2 points).

I enable drawing and the listen for vertexadded. When the _rings marker count equals 2, I disable drawing.

This feels wrong for several reasons:

  1. I access a private variable _rings
  2. Now I disable drawing but to visualise the Line I must reinitiate it in visual mode
  3. To allow the user to move the 2 points of the line, I must reinitiate the Line in edit mode.
  4. In edit mode the splitting of a line between 2 markers must be disabled, is this possible?

Am I missing a simpler way of doing this?

map.pm.enableDraw('Line', {
  snappable: true,
  snapDistance: 20,
});

map.on('pm:drawstart', (event: any) => {
  const { workingLayer } = event;
 
  workingLayer.on('pm:vertexadded', (e: any) => {
    if (workingLayer._rings[0].length >= 2) {

      map.pm.disableDraw('Line', {
        snappable: true,
        snapDistance: 20,
      });
    }
  });
});

Solution

    1. Use layer.getLatLngs() instead of the variable _rings.
    2. don't call map.pm.disableDraw(), finish the shape with map.pm.Draw.Line._finishShape() to add the drawn layer to the map
    3. you can call map.pm.enableGlobalEditMode() to enable editing for all layers or you can enable the wanted layer with layer.pm.enable()
    4. use the option hideMiddleMarkers: true
    map.pm.setGlobalOptions({hideMiddleMarkers: true})
    map.on('pm:drawstart', (event) => {
      const { workingLayer } = event;
    
      workingLayer.on('pm:vertexadded', (e) => {
        if (workingLayer.getLatLngs().length >= 2) {
           map.pm.Draw.Line._finishShape()
        }
      });
    });
    map.pm.enableDraw('Line');
    

    https://jsfiddle.net/falkedesign/7sL02y53/