Google Maps Infowindow with dynamic data
<p>I am using Google distance matrix to calculate distances between different destinations at the same time. I have one origin and several destinations and I want to be able to add infowindows with this data (the distance to destination). The result I am getting at the moment is that the address is undefined. This is because it is outside the for loop, but I am unsure on how to fix this.</p>

<p>My code: </p>

<pre><code>function callback(response, status) {
if(status=="OK") {
    var originList = response.originAddresses;
    var destinationList = response.destinationAddresses;
    var bounds = new google.maps.LatLngBounds;
    var outputDiv = document.getElementById('output');

   var showGeocodedAddressOnMap = function(asDestination) {
      var icon = asDestination ? destinationIcon : originIcon;
      return function(results, status) {
        if (status === 'OK') {
          map.fitBounds(bounds.extend(results[0].geometry.location));
          var markersArray = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location,
            icon: icon
          });

          google.maps.event.addListener(markersArray, 'click', function () {
            infowindow.setContent('&lt;strong&gt;Address&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;' + destinationList[j] + '&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Distance:&lt;/strong&gt; ');
            infowindow.open(map, this);
          });

        } else {
          alert('Geocode was not successful due to: ' + status);
        }
      };
    };            

for (var i = 0; i &lt; originList.length; i++) {
      var results = response.rows[i].elements;
      geocoder.geocode({'address': originList[i]},
          showGeocodedAddressOnMap(false));
      for (var j = 0; j &lt; results.length; j++) {
        geocoder.geocode({'address': destinationList[j]}, showGeocodedAddressOnMap(true));

        /*outputDiv.innerHTML += originList[i] + ' to ' + destinationList[j] +
            ': ' + results[j].distance.text + '&lt;br&gt;';*/

      }
    }

} else {
    alert("Error: " + status);
}
}
</code></pre>