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?
addListener(myMarker, 'dragend', function(evt){ document. getElementById('current'). innerHTML = '<p>Marker dropped: Current Lat: ' + evt. latLng.
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
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With