I am trying to display multiple markers using JSON with geocoding. My code shows all the markers at the correct place but does not show the Correct Infowindow on them or the Correct title. I know it has something to do with closures. But I do not understand it. Please help me out and kindly edit my code and explain why it needs to be edited?
HELP PLEASE!!
points = data.POINTS;
var geocoder;
//var map;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(41.2324, - 98.4160);
var mapOptions = {
zoom: 4,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var infoWindow = new google.maps.InfoWindow();
for (var i = 0, length = points.length; i < length; i++) {
data = points[i],
address = data[1] + ", " + data[2] + ", " + data[3] + ", " + data[4] + ", " + data[5];
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
//Creating a marker and putting it on the map
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: data[4],
animation: google.maps.Animation.DROP
});
// Creating a closure to retain the correct data, notice how I pass the current data in the loop into the closure (marker, data)
(function (marker, points) {
// Attaching a click event to the current marker
//console.log(data[6]);
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data[6] + " " + data[0]);
infoWindow.open(map, marker);
});
})(marker, data);
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
});
}
});
The Answer is the following:
What I needed was to call the add marker function outside the Loop. Thanks for all of your kind consideration of my problem. Hope my Solution will help someone else.