javascriptleafletleaflet-draw

Leaflet.draw emit event to stop drawing


Using leaflet-draw, when i draw with a polyne i need to end the drawing when the second point of the rect is fixed. Listening on 'drawvertex' event two times, in the

mymap.on(L.Draw.Event.DRAWVERTEX, function(e){
    console.log("draw 1st vertex--")
    // console.log(e)

    mymap.on(L.Draw.Event.DRAWVERTEX, function(e){

        console.log("draw 2nd vertex, now need to be closed! ---", e)

        let tmp = e.layers;

        // mymap.emit(L.Draw.Event.DRAWSTOP, function (e){
        //  console.log("draw stopped...")
        // })

        // mymap.emit('draw:drawstop', function (e){
        //  console.log("draw stopped...")
        // })

        // tmp.completeShape()

        // drawnItems.completeShape()
    })
    // if(e.layerType == "polyne"){
    //  console.log(" e la retta..")
    // }
})

I tried with emit, and completeShape function but it didn't work, i tried to use the same method of the button "finish" (when you click in the polyne to draw) but i didin't find the method on the source. Here there is my codebox https://codesandbox.io/s/romantic-jepsen-7esnz?file=/index.html


Solution

  • You can do it triggering the second click automatically to complete the shape

    mymap.on(L.Draw.Event.DRAWVERTEX, function (e) {
    
        const layerIds = Object.keys(e.layers._layers);
    
        if (layerIds.length > 1) {
    
            const secondVertex = e.layers._layers[layerIds[1]]._icon;
    
            requestAnimationFrame(() => secondVertex.click());
    
        }
    });