I made a Google Maps map with a draggable marker. When the user drags the marker, I need to know the new latitude and longitude, but I don't understand what is the best approach to doing that.
How can I retrieve the new coordinates?
I made a Google Maps map with a draggable marker. When the user drags the marker, I need to know the new latitude and longitude, but I don't understand what is the best approach to doing that.
How can I retrieve the new coordinates?
try this
There are a lot of answers to this question, which never worked for me (including suggesting getPosition() which doesn't seem to be a method available for markers objects). The only method that worked for me in maps V3 is (simply) :
Here is the JSFiddle Demo. In Google Maps API V3 it's pretty simple to track the lat and lng of a draggable marker. Let's start with the following HTML and CSS as our base.
Here is our initial JavaScript initializing the google map. We create a marker that we want to drag and set it's draggable property to true. Of course keep in mind it should be attached to an onload event of your window for it to be loaded, but i'll skip to the code:
Here we attach two events
dragstart
to track the start of dragging anddragend
to drack when the marker stop getting dragged, and the way we attach it is to usegoogle.maps.event.addListener
. What we are doing here is setting the divcurrent
's content when marker is getting dragged and then set the marker's lat and lng when drag stops. Google mouse event has a property name 'latlng' that returns 'google.maps.LatLng' object when the event triggers. So, what we are doing here is basically using the identifier for this listener that gets returned by thegoogle.maps.event.addListener
and get the propertylatLng
to extract the dragend's current position. Once we get that Lat Lng when the drag stops we'll display within yourcurrent
div:Lastly, we'll center our marker and display it on the map:
Let me know if you have any questions regarding my answer.
More information can be found at Google Maps API - LatLng