I am completely puzzled here. I have a list of objects, each of which contains a location. I look at this location with google.maps.geocoder and then place a marker for that location on the map.
But for some reason, only one marker appears. I assume this is due to the closure problem that I saw in other threads, but I just can't apply the solution to what I have.
My code is as follows:
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); map.fitBounds(bounds); for (var item in list) { var geocoder = new google.maps.Geocoder(); var geoOptions = { address: item.location, bounds: bounds, region: "NO" }; geocoder.geocode(geoOptions, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { addMarker(map, item, results[0].geometry.location); } else { console.log("Geocode failed " + status); } }); } function addMarker(map, item, location) { var marker = new google.maps.Marker({ map : map, position : location}); marker.setTitle(item.title); var infowindow = new google.maps.InfoWindow( { content : item.body, size : new google.maps.Size(100, 300) }); (function(map, marker) { new google.maps.event.addListener(marker, "click", function() { infowindow.open(map, marker); }); })(map, marker); }
Any help is appreciated.
Update: In order to avoid loop closures, as suggested in the first answer, I changed the code to this:
//This is the entry function codeLocations(list, map) { for (var i = 0; i < list.length; i++) { console.log("Looping " + list[i].location); var geocoder = new google.maps.Geocoder(); var geoOptions = { address: list[i].location, bounds: getBounds(), region: "NO" }; geocoder.geocode(geoOptions, createGeocodeCallback(list[i], map)); } } function createGeocodeCallback(item, map) { console.log("Generating geocode callback for " + item.location); return function(results, status) { if (status == google.maps.GeocoderStatus.OK) { console.log("Geocoding " + item.location + " OK"); addMarker(map, item, results[0].geometry.location); } else { console.log("Geocode failed " + status); } } } function addMarker(map, item, location) { console.log("Setting marker for " + item.location + " (location: " + location + ")"); var marker = new google.maps.Marker({ map : map, position : location}); marker.setTitle(item.title); var infowindow = new google.maps.InfoWindow( { content : item.body, size : new google.maps.Size(100, 300) }); new google.maps.event.addListener(marker, "click", function() { infowindow.open(map, marker); }); }
According to the log operators, now I have the right objects in the right places, which means that the object's objects and locations are different for each marker, but I still get only one marker on my map. How can it be?