Ngo Van Ngo Van - 12 days ago 7
Javascript Question

Get Address when click on Marker - Google Maps

I need some help.

I loaded some point from database and displayed them on Google Maps as markers.

My code:

function DisplayTraficCir(points) {
for (i=0;i<points.length;i++){
var myLatLng = new google.maps.LatLng(points[i].latitude,points[i].longitude)
var marker = new google.maps.Marker({
position: myLatLng,
map: map
});
}
}


And now, I want to get point's information (latitude/longitude) when I click on one of these markers in Google Maps to do some stuff.

Any help, please.
Thanks.

Answer

Use google.maps.event.addListener method:

function DisplayTraficCir(points) {
  for (i=0;i<points.length;i++){
    var myLatLng = new google.maps.LatLng(points[i].latitude,points[i].longitude)
    var marker = new google.maps.Marker({
      position: myLatLng,
      map: map
    });
    google.maps.event.addListener(marker, 'click', function () {
        var lng = points[i].longitue,
            lat = points[i].latitude;
        alert( lat + "-" + lng );
    });
  }
}

Demo