Have following problem, the infowindow, gives the same result on different markers.
When I debug outside geocoder.geocode function it shows the right info, but inside always the same (first one). the suppid part is when i debug the i variable inside it shows the correct value.
var optionMap = {
zoom: 16,
MapTypeId: google.maps.MapTypeId.ROADMAP,
panControl: false,
zoomControl: false,
mapTypeControl: false,
scaleControl: false,
streetViewControl: false,
overviewMapControl: false
};
var map = new google.maps.Map(document.getElementById('map'), optionMap);
var geocoder = new google.maps.Geocoder();
var latlngbounds = new google.maps.LatLngBounds();
var icon = new google.maps.MarkerImage('images/gm_pin.png',
new google.maps.Size(20, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
for(var i = 0; i < arrAddress.length; i++) {
var address = arrAddress[i];
var html_title = "<div class='info'><h4>" + address + "</h4></div>";
geocoder.geocode({
'address': address
}, function (results, status) {
if(status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
icon: icon,
html: html_title,
position: results[0].geometry.location
});
var contentString = '';
var infoWindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'mouseover', function() {
infoWindow.setContent(this.html);
infoWindow.open(map, this);
});
google.maps.event.addListener(marker, 'mouseout', function() {
infoWindow.close(map, this);
});
latlngbounds.extend(results[0].geometry.location);
if(i == arrAddress.length) {
map.fitBounds(latlngbounds);
}
google.maps.event.trigger(map, 'resize')
}
});
}
The call to
Geocoder.geocode(request, callback)is asynchronous. When the server responds the callback function is called. Usually by this time, the for loop has already finished. This can have exactly the results that you describe, e.g. each marker has the same content, because the marker is created in the callback, which happens after the loop is finished, and thus it will use the last value that was inhtml_title.The way to fix this is by creating a closure inside the loop, that will ‘capture’ the variable
html_titleinside the loop. This way, the callback will use the correct value ofhtml_title.A typical explicit closure in JavaScript looks like this:
In your code, the closure will need to capture an address during the loop: