title: Problem with Google Maps and JavaScript for() loop
body: <p>I have a website where users can search for professional wrestling events in the United Kingdom by entering there location. The site uses the Google Maps API and a bespoke API to query the database and return the events via AJAX.</p>
  
  <p>The JavaScript function I'm using to iterate over results from my API looks like this:</p>
  
  <pre><code>function setMarkers(map, events) {
      var geocoder = new google.maps.Geocoder();
      for (var i=0; i &lt; events.length; i++) {
          var wrestling_event = events[i];
          console.log(wrestling_event);
          var image_a = '/images/marker.png';
          var image_b = '/images/marker-over.png';
          geocoder.geocode({ address: wrestling_event.venue.post_code }, function(results, status) {
              if (status == google.maps.GeocoderStatus.OK) {
                  var marker = new google.maps.Marker({
                      position: results[0].geometry.location,
                      map: map,
                      icon: image_a
                  });
                  var infowindow = new google.maps.InfoWindow({
                      content: '&lt;p&gt;&lt;strong&gt;' + wrestling_event.date + ': ' + wrestling_event.name + '&lt;/strong&gt;&lt;br /&gt;' +
                               wrestling_event.venue.name + ',&lt;br /&gt;' +
                               wrestling_event.venue.street_address + ',&lt;br /&gt;' +
                               wrestling_event.venue.city + ',&lt;br /&gt;' +
                               wrestling_event.venue.post_code + '&lt;/p&gt;'
                  });
                  google.maps.event.addListener(marker, 'mouseover', function() {
                      marker.setIcon(image_b);
                  });
                  google.maps.event.addListener(marker, 'mouseout', function() {
                      marker.setIcon(image_a);
                  });
                  google.maps.event.addListener(marker, 'click', function() {
                      infowindow.open(map, marker);
                  });
              }
          });
      }
  };
  </code></pre>
  
  <p>This is adapted from the Google Maps API sample, found here: <a href="http://code.google.com/apis/maps/documentation/javascript/examples/icon-complex.html" rel="nofollow">http://code.google.com/apis/maps/documentation/javascript/examples/icon-complex.html</a></p>
  
  <p>The issue I'm having is, if I have multiple results returned from the bespoke API, my JavaScript function is printing the same event over and over, despite logging the result of the <code>wrestling_event</code> object.</p>
  
  <p>The <code>wrestling_event</code> variable seems to get overwritten (or not after the first iteration in the <code>for()</code> loop) inside the geocoding block. Is there a reason for this?</p>