96

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?

MAXE
  • 4,978
  • 2
  • 45
  • 61
Genadinik
  • 18,153
  • 63
  • 185
  • 284

8 Answers8

142

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.

<div id='map_canvas'></div>
<div id="current">Nothing yet...</div>

#map_canvas{
    width: 400px;
    height: 300px;
}

#current{
     padding-top: 25px;
}

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:

var map = new google.maps.Map(document.getElementById('map_canvas'), {
    zoom: 1,
    center: new google.maps.LatLng(35.137879, -82.836914),
    mapTypeId: google.maps.MapTypeId.ROADMAP
});

var myMarker = new google.maps.Marker({
    position: new google.maps.LatLng(47.651968, 9.478485),
    draggable: true
});

Here we attach two events dragstart to track the start of dragging and dragend to drack when the marker stop getting dragged, and the way we attach it is to use google.maps.event.addListener. What we are doing here is setting the div current'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 the google.maps.event.addListener and get the property latLng to extract the dragend's current position. Once we get that Lat Lng when the drag stops we'll display within your current div:

google.maps.event.addListener(myMarker, 'dragend', function(evt){
    document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
});

google.maps.event.addListener(myMarker, 'dragstart', function(evt){
    document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';
});

Lastly, we'll center our marker and display it on the map:

map.setCenter(myMarker.position);
myMarker.setMap(map);

Let me know if you have any questions regarding my answer.

KJYe.Name
  • 16,969
  • 5
  • 48
  • 63
51
var lat = marker.getPosition().lat();
var lng = marker.getPosition().lng();

More information can be found at Google Maps API - LatLng

maxshuty
  • 9,708
  • 13
  • 64
  • 77
  • how do you instantiate `marker` before calling methods on it? for example, i am looking at https://developers.google.com/maps/documentation/javascript/examples/places-searchbox and after a search has been done and a marker appears, how do i get the lat/long of that marker? – user1063287 Sep 02 '20 at 11:08
32

You could just call getPosition() on the Marker - have you tried that?

If you're on the deprecated, v2 of the JavaScript API, you can call getLatLng() on GMarker.

Bern
  • 7,808
  • 5
  • 37
  • 47
no.good.at.coding
  • 20,221
  • 2
  • 60
  • 51
  • I think where my confusion was is when to call the getPosition() - is it something I have to add to the constructor so that it knows to ask for the coordinates when the marker is moved? – Genadinik Mar 13 '11 at 15:39
  • @Genadinik The example I linked to in my edit might of help; it shows how to attach a listener for drag events where you can query the marker for it's position and use it however you'd like. – no.good.at.coding Mar 13 '11 at 15:43
  • Ah cool, and if I want to store the coordinates in the session or the db, should I do it through an AJAX call? Or is there a simpler way? – Genadinik Mar 13 '11 at 15:46
  • I can't think of anything simpler than a quick Ajax post with the marker id and it's current coordinates :) But you could consider batching updates or at least waiting a few seconds until after the drag is completed and seeing that the user doesn't begin any more drags so that you don't inundate the server with requests while markers are in the process of being dragged - wait until the positions are stable, so to speak. This of course depends on how far behind you can afford to have your server-side state compared to what the client sees. – no.good.at.coding Mar 13 '11 at 15:52
  • 1
    `getPosition()` returns an object, so to specifically get latitude/longitude, you'll have to call `lat()` and `lng()` respectively from that. – Jeff Puckett Sep 12 '17 at 16:18
22

try this

var latlng = new google.maps.LatLng(51.4975941, -0.0803232);
var map = new google.maps.Map(document.getElementById('map'), {
    center: latlng,
    zoom: 11,
    mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
    position: latlng,
    map: map,
    title: 'Set lat/lon values for this property',
    draggable: true
});

google.maps.event.addListener(marker, 'dragend', function (event) {
    document.getElementById("latbox").value = this.getPosition().lat();
    document.getElementById("lngbox").value = this.getPosition().lng();
});
Rolwin Crasta
  • 4,219
  • 3
  • 35
  • 45
8
// show the marker position //

console.log( objMarker.position.lat() );
console.log( objMarker.position.lng() );

// create a new point based into marker position //

var deltaLat = 1.002;
var deltaLng = -1.003;

var objPoint = new google.maps.LatLng( 
  parseFloat( objMarker.position.lat() ) + deltaLat, 
  parseFloat( objMarker.position.lng() ) + deltaLng
);

// now center the map using the new point //

objMap.setCenter( objPoint );
Jeff Puckett
  • 37,464
  • 17
  • 118
  • 167
Thiago Mata
  • 2,825
  • 33
  • 32
3

var map = new google.maps.Map(document.getElementById('map_canvas'), {
  zoom: 10,
  center: new google.maps.LatLng(13.103, 80.274),
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

var myMarker = new google.maps.Marker({
  position: new google.maps.LatLng(18.103, 80.274),
  draggable: true
});

google.maps.event.addListener(myMarker, 'dragend', function(evt) {
  document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
});
google.maps.event.addListener(myMarker, 'dragstart', function(evt) {
  document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';
});
map.setCenter(myMarker.position);
myMarker.setMap(map);

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + position.coords.latitude + ' Current Lng: ' + position.coords.longitude + '</p>';
  var myMarker = new google.maps.Marker({
    position: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
    draggable: true
  });
  google.maps.event.addListener(myMarker, 'dragend', function(evt) {
    document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
  });
  google.maps.event.addListener(myMarker, 'dragstart', function(evt) {
    document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';
  });
  map.setCenter(myMarker.position);
  myMarker.setMap(map);
}
getLocation();
#map_canvas {
  width: 980px;
  height: 500px;
}

#current {
  padding-top: 25px;
}
<script src="http://maps.google.com/maps/api/js?sensor=false&.js"></script>
<!DOCTYPE html>
<html lang="en">

<head>

</head>

<body>
  <section>
    <div id='map_canvas'></div>
    <div id="current">
      <p>Marker dropped: Current Lat:18.103 Current Lng:80.274</p>
    </div>
  </section>


</body>

</html>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • 1
    While this code may answer the question, providing information on how and why it solves the problem improves its long-term value. – L_J Jul 25 '18 at 19:48
2

You should add a listener on the marker and listen for the drag or dragend event, and ask the event its position when you receive this event.

See http://code.google.com/intl/fr/apis/maps/documentation/javascript/reference.html#Marker for the description of events triggered by the marker. And see http://code.google.com/intl/fr/apis/maps/documentation/javascript/reference.html#MapsEventListener for methods allowing to add event listeners.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
-3

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) :

var lat = marker.lat();
var long = marker.lng();
Pr Shadoko
  • 1,649
  • 2
  • 15
  • 16