2
votes

I may be missing some fundamental law in JavaScript here, quite possibly, but I have a question regarding the latlng position of a Google Maps marker after it is dragged.

I am successfully adding markers to a map, and assigning those added markers to a variable, or to be more precise, I'm using jQuery to add those markers to the data of the map's div element, using jQuery.data().

Now, the problem I have arises when I drag those markers around the map. I understand the dragend event, and how to fire/capture it and it's data, including the new latlng position after the drag. That being said, I was of the understanding that objects in JavaScript are passed by reference, so what I can't understand is why the position of the marker reference stored in the element isn't updated to reflect the new position automatically?

I guess it could be one of the following:

  1. Objects passed into the data of an element are duplicated, not passed by reference, and therefore a jQuery problem.
  2. Google Maps doesn't automatically update the latlng positions of it's markers, stored in variables or data nodes, and therefore a Google Maps problem.
  3. I have to physically fire the dragend event myself to update the position (sounds like an odd solution).

I'm basically querying this to see if I need to log it as an issue anywhere, or whether I'm just being an idiot. Any input from other hardened Google Mappers would really help me here.

Cheers in advance.

1
If I could retract a question without looking like an idiot, I would. It certainly does update the position, I just forgot to re-output into my JS Console. Duh. - designermonkey
I believe you can delete the question! - Tomas
Too late now, my idiocy will remain forever. - designermonkey
:-)) no, you can flag it and ask admin to delete it :-) - Tomas

1 Answers

7
votes

I've seen you have solved your problem but maybe it's helpful for others reading this question.

Google Maps is overwriting the position of a Marker with a new LatLng-Object after dragend. If you store the position (LatLng-Object) of a marker in a variable, the variable holds a reference to the previously defined LatLng-Object. After the dragend the position of the marker gets updated but not the LatLng-Object itself.

Let's have a look at the following code:

var ll  = new google.maps.LatLng(52, 0.054);
var m   = new google.maps.Marker({
    position: ll,
    draggable: true,
    title: 'hello world'    
});

google.maps.event.addListener(m, 'dragend', function(ev){
    alert(ll.lat() + ' ' + ll.lng()); // always the same LatLng-Object...
    alert(m.getPosition()); // new LatLng-Object after dragend-event...
});