2

The "drag", "dragstart" and "dragend" events in the Google Maps V3 API each pass a mouseEvent to the registered callback function.

However - this event does not contain any information as to which marker is being dragged. How can I determine that?

This is even more complicated if you are just looking at the "dragend" event - which would only have the new coordinates, making it impossible to even infer from the coordinates.

I'd assume there's got to be an easy way to just determine which marker is being dragged...

Brad
  • 10,528
  • 7
  • 48
  • 68

1 Answers1

2

I would attach add the drag event to the marker using a listener when it is created.

google.maps.event.addListener(marker, 'dragend', function() {
                //do something with the event.
            });

here is an example fiddle: http://jsfiddle.net/2YQg6/10/ (Dont mind the other stuff I just edited a fiddle I have used before to handle draggable markers.)

The relavant code is in the marker creation loop:

//geo code and build markers for each list item.
for (var i = 0; i < $listItems.length; i++) {
    geocoder.geocode({
        'address': $($listItems[i]).text()
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var marker = new google.maps.Marker({
                position: results[0].geometry.location,
                map: map,
                draggable: true,
                originalPos: results[0].geometry.location
            });

            google.maps.event.addListener(marker, 'dragend', function() {
                infoWindow.setContent("marker originally at this position: " + this.originalPos + " was dragged to: " + this.position);
                infoWindow.open(map, this);
            });


            markers.push(marker);
        }        

});
}
Bryan Weaver
  • 4,405
  • 1
  • 27
  • 38
  • 1
    Long story short, the "this" keyword in your listener function will point to your marker – Danny Cohn Sep 11 '11 at 01:14
  • cannot stress enough the usefulness of Dannys comment, as i cannot find that info anywhere in Googles documentation. – ghost23 Jan 09 '13 at 13:26
  • `this` would not be in Google's documentation since it is part of the JavaScript language. http://stackoverflow.com/questions/3127429/javascript-this-keyword – Bryan Weaver Jan 09 '13 at 14:28
  • 1
    @Bryan Weaver ... how can I find marker instance using ES6's anonymous function syntax i.e. using ()=>{ } for the dragend event handler ? – Shivam Mar 16 '17 at 05:45