Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get latitude and longitude of marker (onclick)

How can you create an listener to a marker and get its latitude and longitude. When I create an listener to each marker of a click event, I can do stuff like alert on the click, but how can I get the coords of the marker i.e click -> this.getLat/getLng, etc. when clicked on?

like image 581
MacMac Avatar asked Jun 16 '11 15:06

MacMac


People also ask

How do you find lat long from markers?

addListener(myMarker, 'dragend', function(evt){ document. getElementById('current'). innerHTML = '<p>Marker dropped: Current Lat: ' + evt. latLng.


2 Answers

Try this:

marker = new google.maps.Marker({
             position: latlng,
             map: map                    
}); //end marker

//Add listener
google.maps.event.addListener(marker, "click", function (event) {
                    alert(this.position);
}); //end addListener
like image 84
Bryan Weaver Avatar answered Mar 01 '23 20:03

Bryan Weaver


As a followup to Bryan Weaver's excellent answer, if you want to SAVE latitude and longitude separately, you must use lat() and lng(). the position property is not a regular string.

bryan's code would become:

marker = new google.maps.Marker({
             position: latlng,
             map: map                    
}); //end marker

//Add listener
google.maps.event.addListener(marker, "click", function (event) {
    var latitude = this.position.lat();
    var longitude = this.position.lng();
    alert(this.position);
}); //end addListener

you can apply lat() and lng() directly on a variable (latLng)

    var latitude = latLng.lat();
    var longitude = latLng.lng();
like image 27
tony gil Avatar answered Mar 01 '23 21:03

tony gil