15

for a small project I am working on, I need to be able to place a marker on a leaflet.js powered image-map and update the position of this marker, if it gets dragged. I use the following code to try this, but it fails. I get the error 'marker not defined'. I don't know why it's not working - maybe you guys could help me out? ;)

function onMapClick(e) {
    gib_uni();
    marker = new L.marker(e.latlng, {id:uni, icon:redIcon, draggable:'true'};
    map.addLayer(marker);
};

marker.on('dragend', function(event){
    var marker = event.target;
    var position = marker.getLatLng();
    alert(position);
    marker.setLatLng([position],{id:uni,draggable:'true'}).bindPopup(position).update();
});
Cœur
  • 37,241
  • 25
  • 195
  • 267
kirijanker
  • 197
  • 1
  • 2
  • 9

1 Answers1

28

In the code snippet above, marker is not defined at the time the event handler is added. Try the following where the dragend listener is added immediately following the creation of the Marker:

function onMapClick(e) {
    gib_uni();
    marker = new L.marker(e.latlng, {id:uni, icon:redIcon, draggable:'true'});
    marker.on('dragend', function(event){
            var marker = event.target;
            var position = marker.getLatLng();
            console.log(position);
            marker.setLatLng(position,{id:uni,draggable:'true'}).bindPopup(position).update();
    });
    map.addLayer(marker);
};

You were also missing a bracket at the end of your new L.Marker() line.

You also put position into an array in the call to setLatLng but it is already a LatLng object.

nothingisnecessary
  • 6,099
  • 36
  • 60
user2680198
  • 306
  • 3
  • 4
  • 1
    Dunno which version you were using guys but it is `marker.setLatLng([position.lat, position.lng], ...` instead of `marker.setLatLng([position], ...` now. – Amio.io Mar 11 '16 at 08:43
  • I updated the answer with correct usage.. author did not need to put `position` into an array because it was already a `LatLng` object which is the output of `getLatLng()` and the input to `setLatLng()` per Leaflet docs: http://leafletjs.com/reference.html#marker – nothingisnecessary Jun 09 '16 at 17:31