Search code examples
leafletmarkers

make multiple markers draggable


I use an Array to create a couple of markers in my leaflet map for Photos with Geolocations which works fine:

for (var p of ArrayofData) {
    var lat = p.lat;
    var lon = p.lon;
    var markerLocation = new L.LatLng(lat, lon);
    var marker = new L.Marker(markerLocation,{
        draggable: 'true',
        id: p.Filename
    });
    mymap.addLayer(marker);
}

to enable users to change their photo location I need them to drag those markers around and then I can read the new location:

marker.on('dragend', function (e) {
    // Get position of dropped marker
    var latLng = e.target.getLatLng();
    console.log ("id:"+e.target.options.id);
    console.log ("NewLocation:"+latLng);
});

As all of my markers have the same constructor it seems as if this script only works with the last marker. All others are draggable but do not give back any feedback when released.

Does anybody know, how I can access all of them?


Solution

  • You can do that by adding those drag event handlers inside your for loop.

    for (var p of data) {
        var lat = p.lat;
        var lon = p.lon;
        var markerLocation = new L.LatLng(lat, lon);
        var marker = new L.Marker(markerLocation,{
            draggable: 'true',
            id: p.Filename
        });
    
        map.addLayer(marker);
    
        marker.on('dragend', function (e) {
            // Get position of dropped marker
            var latLng = e.target.getLatLng();
            console.log ("id:"+e.target.options.id);
            console.log ("NewLocation:"+latLng);
        });
    }
    

    Also I highly recommend that you keep track of your markers by adding them to an array.

    var markers = [];
    
    for (var p of data) {
        var lat = p.lat;
        var lon = p.lon;
        var markerLocation = new L.LatLng(lat, lon);
        var marker = new L.Marker(markerLocation,{
            draggable: 'true',
            id: p.Filename
        });
    
        map.addLayer(marker);
    
        marker.on('dragend', function (e) {
            // Get position of dropped marker
            var latLng = e.target.getLatLng();
            console.log ("id:"+e.target.options.id);
            console.log ("NewLocation:"+latLng);
        });
    
        markers.push(marker);
    } 
    

    Demo