0

I am trying to write a method that creates Leaflet markers with a function updateRoute which should be called whenever the marker is moved.

My problem is that I can't find the index of the marker that was moved as the wayPointIteration variable is evaluated as the total number of markers. I understand why it doesn't work like that now but I don't know how the method can be executed with knowledge of the iteration of that marker.

function updateWayPointsOnMap() {
    let options = {draggable: true};
    let wayPointIteration = 1;
    
    getRouteWayPoints().forEach(wayPoint => {
        let newMarker = L.marker([wayPoint.lat, wayPoint.lng], options).bindTooltip("Way point " + wayPointIteration).addTo(map)
            .on('move', function updateRoute(move) {
                getRouteWayPoints()[wayPointIteration - 1] = move.latlng;
                updateMap();
        });
        routeMarkers.push(newMarker);
        wayPointIteration ++;
    });
}
algorhythm
  • 3,304
  • 6
  • 36
  • 56
  • 1
    See https://stackoverflow.com/questions/111102/how-do-javascript-closures-work and the `index` parameter of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach – IvanSanchez Jun 28 '20 at 15:45
  • Thanks, worked a treat! – algorhythm Jun 28 '20 at 20:50

0 Answers0