回调函数问题

时间:2013-09-20 13:00:02

标签: javascript jquery function google-maps callback

这里我有一个函数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

1 个答案:

答案 0 :(得分: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);