title: Having Trouble With Closure In Javascript
body: <p>I'm trying to pass an array into a function and then use the information in that array to initialize a google map.  However, when I click on a marker on the map, an error is produced which says: </p>
  
  <blockquote>
    <p>Unable to get value of the property 'popupHtml': object is null or
    undefined</p>
  </blockquote>
  
  <p>The reason for creating the function is so that the javascript code can be moved to a seperate .js file, thus becoming seperate from the html file.  Is there anyway this problem can be corrected?  Here's all my code (I put a comment in to mark where the error is occuring...):</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  
  &lt;html&gt;
  &lt;head&gt;    
      &lt;script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"&gt;&lt;/script&gt;
      &lt;script type="text/javascript"&gt;
          window.onload = function ()
          {
              function loadMap(markers)
              {
                  var options =
                  {
                      center: new google.maps.LatLng(40.775813, -73.970786),
                      zoom: 17,
                      mapTypeId: google.maps.MapTypeId.ROADMAP
                  };
                  var map = new google.maps.Map(document.getElementById('map'), options);
  
                  var points = new Array();
                  for (var i = 0; i &lt; markers.length; i++)
                      points.push(new google.maps.LatLng(markers[i].lat, markers[i].lon));
                  var infoWindow = new google.maps.InfoWindow();
                  for (var i = 0; i &lt; markers.length; i++)
                  {
                      var googleMarker = new google.maps.Marker({ position: points[i], map: map, title: markers[i].title });
                      google.maps.event.addListener(
                          googleMarker,
                          'click',
                          function ()
                          {
                              // The following line is where the error is occuring:
                              infoWindow.setContent(markers[i].popupHtml);
                              infoWindow.open(map, googleMarker);
                          });
                  }
              };
  
              loadMap([{
                  "lat": "40.776512",
                  "lon": "-73.970293",
                  "popupHtml": "\u003cdiv\u003eHello world - from marker 1!\u003c/div\u003e",
                  "title": "Marker 1!"
              },
              {
                  "lat": "40.774659",
                  "lon": "-73.971548",
                  "popupHtml": "\u003cdiv\u003eHello world - from marker 2!\u003c/div\u003e",
                  "title": "Marker 2!"
              }]);
          };
      &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
      &lt;div id="map" style="width: 680px; height: 400px;"&gt;&lt;/div&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>