geocoding is an asynchronous request. Therefore, when you use geocoding inside a for loop, the loop is already completed, when you get the results, i will always be 1 and point to the last element of people.
What you can do: divide the creation marker into 2 functions. 1 for a loop that calls a second function that creates tokens:
remove the current setMarkers function and add the following 2 functions to your script:
function setMarkers(map,people) { for (var i = 0; i < people.length; i++) { setMarker(map, people[i]) } } function setMarker(map, people) { var p=people; geocoder = new google.maps.Geocoder(); geocoder.geocode( { 'address': p["address"] }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); var marker = new google.maps.Marker({ position: results[0].geometry.location, map: map, html: p["address"] }); var contentString = "Some content"; google.maps.event.addListener(marker, "click", function () { infowindow.setContent(this.html); infowindow.open(map, this); }); } else { alert("Geocode was not successful for the following reason: " + status); } }); }
The rest of your script may remain as it is.
source share