title: Click Listeners in Loop for rectangle array -- Closure
body: <p>My question is very similar to this post but the solution doesn't work for me for some reason --> <a href="https://stackoverflow.com/questions/13907103/click-listeners-in-loop-array-and-closure">Click Listeners in Loop - Array and Closure</a></p>
  
  <p>Users can click on google map api; I want to make rectangles of 2kmx2km wherever the user clicks, add these to a rectangle array, and add listeners to them for clicks. The rectangles show up and the rectangle array is populated, but the click listeners just. don't. work. I'm at my wit's end and have endlessly researched and tried various solutions; any help will be much appreciated!</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var SFLatLng = {lat: 37.7739, lng: -122.4312};
  var map;
  var rectangleArray = [];
  var rectangleArraySize = 0;
  
  function initMap() {
      map = new google.maps.Map(document.getElementById('map'), {
           center: SFLatLng,
           zoom: 12,
           scaleControl: true,
      });
      doStuff();
  } //end map init
  
  function doStuff() {
        //make rectangle of size 2kmx2km on map click
        map.addListener('click', function(e) {      
     var bounds = calcBounds(e.latLng, new google.maps.Size(2000,2000));
     addRectangleToMap(bounds);
        });
  
       function addRectangleToMap(boundsObj) {
    rectangleArray[rectangleArraySize] = {
         rect: new google.maps.Rectangle({
     map: map,
                   bounds: boundsObj,
                   fillColor:'red',
                   fillOpacity: 0.3,
                   strokeOpacity: 0,
                   clickable: true,
                   zIndex: 1
      })
     };
     rectangleArraySize++;
       }
  
       function addClickListener(rectObj) {
           google.maps.event.addListener(rectObj.rect, 'click', function() {
                alert("clicked!")
           });
       }
  
       for (var i = 0; i &lt; rectangleArray.length; i++ ) {       
            if(rectangleArray[i]) { //safety
                addClickListener(rectangleArray[i]);
            }       
       }
  }
  
  /** @this {google.maps.Rectangle} */
  function calcBounds(center,size){
      //Calculates bounds ...
  }</code></pre>
  </div>
  </div>
  </p>