title: Google Maps event listeners not working properly in a Javascript 'for' loop
body: <p>I'm trying to set up a Google map instance where some content is dynamically generated for a set of points.</p>
  
  <p>Right now, I'm using a for loop to loop through any number of latitude and longitude values and create markers are those points on the map.</p>
  
  <p>I'm trying to add info windows that correspond to each of these markers and have them pop up when you click the markers.</p>
  
  <p>However, I'm having a little bit of trouble. It looks like my for loop that creates basically everything is working without fail, apart from the eventListener section:</p>
  
  <pre><code>function drawMap(points) {
      popUps = new Array();
      infoWindows = new Array();
      positions = new Array();
  
      contents = '&lt;div id = "content"&gt;' +
          '&lt;div id="siteNotice"&gt;' +
          '&lt;/div&gt;' +
          '&lt;p id="firstHeading" class="firstHeading"&gt;Position&lt;/h1&gt;' +
          '&lt;/div&gt;';
  
      infowindow = new google.maps.InfoWindow({
          content: contents
      });
  
      for( i = 0; i &lt; points.length; i++ ){
          positions[i] = new google.maps.Marker({ position: 
          latlng[i], 
          map:map, 
          title:"Position"});
  
          popUps[i] = '&lt;div id = "content"&gt;' +
              '&lt;div id="siteNotice"&gt;' +
              '&lt;/div&gt;' +
              '&lt;p id="firstHeading" class="firstHeading"&gt;Position&lt;/h1&gt;' +
              '&lt;/div&gt;';
  
          infoWindows[i] = new google.maps.InfoWindow({
              content: popUps[i]
          });
  
      // everything up to this point works fine, I can reference it all manually
      // and get back the expected value.
  
          google.maps.event.addListener(positions[i], 'click', function(){
              infoWindows[i].open(map, positions[i]);                 
          });
  
      // if I change each instance of "i" to "0" here, I'll get a popup on the
      // expected marker containing content that I defined in this for loop. Same for
      //  "1" and "2." But "i" doesn't work.
      }
  }
  </code></pre>
  
  <p>where "map" is an instance of google.maps.Map and each instance of popUps will differ in the final product.</p>
  
  <p>I call this function when the page loads, which adds positions and markers to my map:</p>
  
  <pre><code>drawMap([[13.283 , 162.232], [18.232 , 112.223], [17.233, 80.293]]);
  </code></pre>
  
  <p>Does anyone know why I'm unable to create eventListeners dynamically? Any help would be greatly appreciated! </p>
  
  <p>Thanks in advance. :)</p>
  
  <p>Edit: </p>
  
  <p>Turns out, the requirements here are only to have the divs pop up when the page loads. I didn't even need the event listener...</p>
  
  <p>However, both answers were good and helped me figure out how to make the original code work, so thanks. :D</p>