0

这里我有一个函数calculateDistance,它必须返回两个地方和时间之间的距离,所以我写:

 function calculateDistances(start,stop) {
  var service = new google.maps.DistanceMatrixService();
  service.getDistanceMatrix(
    {
      origins: [start],
      destinations: [stop],
      travelMode: google.maps.TravelMode.DRIVING,
      unitSystem: google.maps.UnitSystem.METRIC,
      avoidHighways: false,
      avoidTolls: false
    }, callback);
}
  function callback(response, status) {
  if (status != google.maps.DistanceMatrixStatus.OK) {
    alert('Error was: ' + status);
  } else {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;


    for (var i = 0; i < origins.length; i++) {
      var results = response.rows[i].elements;
      for (var j = 0; j < results.length; j++) {
       var xxx= "";
        xxx += origins[i] + ' to ' + destinations[j]
            + ': ' + results[j].distance.text + ' in '
            + results[j].duration.text + '<br>';
     return xxx;
      }
    }
  }
}

之后我编写了一个代码来实现这个功能到我的 js 代码中:

//Start function for calculate distance
        var start = document.getElementById("from").value;
        var stop = place.formatted_address;
        contentStr += '<p>'+ calculateDistances(start,stop); + '</p>';

        //I open rendered HTML in jquery dialog when user click on marker
        $(contentStr).dialog({
          modal:true
      });

我只是得到 HTML: undefined 并在控制台中:Uncaught TypeError: Cannot read property '__e3_' of null

我该如何解决这个问题?完整代码:http: //jsbin.com/EVEWOta/96/edit

4

1 回答 1

1

DirectionsService 是异步的。您不能从回调函数“返回”结果。当服务器返回结果时(在回调函数中),您必须使用结果。未测试:

 function calculateDistances(start,stop) {
  var service = new google.maps.DistanceMatrixService();
  service.getDistanceMatrix(
    {
      origins: [start],
      destinations: [stop],
      travelMode: google.maps.TravelMode.DRIVING,
      unitSystem: google.maps.UnitSystem.METRIC,
      avoidHighways: false,
      avoidTolls: false
    }, callback);
}
  function callback(response, status) {
  if (status != google.maps.DistanceMatrixStatus.OK) {
    alert('Error was: ' + status);
  } else {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;
    var xxx= "";

    for (var i = 0; i < origins.length; i++) {
      var results = response.rows[i].elements;
      for (var j = 0; j < results.length; j++) {

        xxx += origins[i] + ' to ' + destinations[j]
            + ': ' + results[j].distance.text + ' in '
            + results[j].duration.text + '<br>';
      }
      var contentStr += '<p>'+ xxx + '</p>';
    }    
    //I open rendered HTML in jquery dialog when user click on marker
    $(contentStr).dialog({
      modal:true
    });
  }
}

//Start function for calculate distance
var start = document.getElementById("from").value;
var stop = place.formatted_address;
calculateDistances(start,stop);
于 2013-09-20T13:34:28.770 回答