I'm implementing geocoder using google map api v3 (javascript). I'm putting mutiple markers and when i click on marker i want the corresponding address to come in the info-window. But when i click on the marker, initially the default value of address(As per code Geo-Address Unavailable!) is coming and when i click the second marker it is having the address of the previously clicked marker. I'm attaching the piece of code.
var addr=" Geo-Address Unavailable!";
var geocoder = new google.maps.Geocoder();
for(var i = 0; i < latLngs.length-1; i++){ //latLngs is the array of latlongs
marker = new google.maps.Marker({
position: latlng,
id:markerId,
icon: image,
map: map,
animation : google.maps.Animation.DROP,
});
}
markers[markerId] = marker;
var infowindow = new google.maps.InfoWindow({
content: "loading..."
});
google.maps.event.addListener(marker, "click", function () {
geocoder.geocode({'latLng': this.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
addr = results[0].formatted_address;
}
});
infowindow.setContent(addr);
infowindow.open(map, this);
});
Geocoding is asynchronous. You have to use the returned value inside the callback from the geocoder.
What is happening: