Search code examples
javascriptleafletdragmarkerpolyline

Leaflet - How to match marker and polyline on drag and drop #2 (delete the last marker and polyline with button click)


I stuck again. Putting the markers and connecting them is working. Thanks to "Falke Design" :-) Now I would like to remove the last marker (Waypoint), when I click on the "Delete last Waypoint" button. I manged to do it and working well, but the last line is not removed. Full code You can find here: Demo code

This issue shall be in function delteLastWp() row # 218

function delteLastWp(id) { 

    var new_markers = []
    marker_new.forEach(function(marker) {
        if (marker._id == id) {
            map.removeLayer(marker);
        }
        else new_markers.push(marker)
    })
    marker_new = new_markers

    // remove the last point/line in the polyline as well ! 
    var new_polylines = []  
    tempLine.forEach(function(polyline) {
        if (polyline._id == id) {
            map.removeLayer(polyline); //*** This si not working ****
            // remove the last point in the polyline as well !
        }
        else new_polylines.push(polyline)
    })      
}

Please help me! Thank You very much in advance :-)


Solution

  • Change your code to:

    function delteLastWp()  // ## with the last segment of the polyline 
    { //marker_new[lineCount]
    
        var new_markers = []
        marker_new.forEach(function(marker) {
            if (marker._id == lineCount) {
                map.removeLayer(marker);  // Working :-)
          lineCount--;
            }
            else new_markers.push(marker)
        })
        marker_new = new_markers;
    
        var latlngs = tempLine.getLatLngs()
        latlngs.splice(-1); 
        tempLine.setLatLngs(latlngs);
            
    }
    

    You load the latlngs from the line, then remove the last latlng and then add it again to the tempLine