带有动态数据的Google Maps Infowindow

时间:2016-10-31 10:22:42

标签: javascript api google-maps matrix maps

我正在使用Google距离矩阵同时计算不同目的地之间的距离。我有一个起点和几个目的地,我希望能够添加这个数据(到目的地的距离)的infowindows。我目前得到的结果是地址未定义。这是因为它在for循环之外,但我不确定如何解决这个问题。

我的代码:

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('<strong>Address</strong><br /><br />' + destinationList[j] + '<br /><br /><strong>Distance:</strong> ');
            infowindow.open(map, this);
          });

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

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

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

      }
    }

} else {
    alert("Error: " + status);
}
}

1 个答案:

答案 0 :(得分:0)

一个选项是在showGeocodedAddressOnMap函数中的地址上获取函数闭包。

var showGeocodedAddressOnMap = function(address, asDestination) {
  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(evt) {
        infowindow.setContent('<strong>Address</strong><br /><br />' + address + '<br /><br /><strong>Distance:</strong> ');
        infowindow.open(map, this);
      });
    } else {
      alert('Geocode was not successful due to: ' + status);
    }
  };
};

TopShelf

代码段

&#13;
&#13;
function initialize() {
  map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: {
        lat: 55.53,
        lng: 9.4
      },
      zoom: 10,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

  var service = new google.maps.DistanceMatrixService;
  service.getDistanceMatrix({
    origins: [origin1, origin2],
    destinations: [destinationA, destinationB],
    travelMode: 'DRIVING',
    unitSystem: google.maps.UnitSystem.METRIC,
    avoidHighways: false,
    avoidTolls: false
  }, callback);
}

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(address, asDestination) {
      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,
          });
          google.maps.event.addListener(markersArray, 'click', function(evt) {
            infowindow.setContent('<strong>Address</strong><br /><br />' + address + '<br /><br /><strong>Distance:</strong> ');
            infowindow.open(map, this);
          });
        } else {
          alert('Geocode was not successful due to: ' + status);
        }
      };
    };

    for (var i = 0; i < originList.length; i++) {
      var results = response.rows[i].elements;
      geocoder.geocode({
          'address': originList[i]
        },
        showGeocodedAddressOnMap(originList[i], false));
      for (var j = 0; j < results.length; j++) {
        geocoder.geocode({
          'address': destinationList[j]
        }, showGeocodedAddressOnMap(destinationList[j], true));
      }
    }
  } else {
    alert("Error: " + status);
  }
}
google.maps.event.addDomListener(window, "load", initialize);

var geocoder;
var map;
var origin1 = {
  lat: 55.93,
  lng: -3.118
};
var origin2 = 'Greenwich, England';
var destinationA = 'Stockholm, Sweden';
var destinationB = {
  lat: 50.087,
  lng: 14.421
};
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
&#13;
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
&#13;
&#13;
&#13;