我正在尝试找出一种启动google distancematrix调用的方法,我需要在使用javascript和jquery继续执行程序之前返回结果。 请有人帮忙 代码样本的想法。 我有多条腿用于距离。即: 腿1开始和结束点 腿2开始和结束点 第3节开始和结束点 我想要做的是计算不同腿之间的旅行时间,所以 腿1完成驾驶员需要开始腿2.所以打电话以获得腿1完成和腿2之间的距离开始。 然后继续下一个计算。 我已经有腿距了,我的代码如下:
var driving = 0;
calculateDistances();
code to work with the calculatedistances() result here
function calculateDistances() {
//alert(origin+','+destination);
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
//set origin and destination points
origins: [origin],//, origin2],
destinations: [destination],
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 outputDiv = '';
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
//addMarker(origins[i], false);
for (var j = 0; j < results.length; j++) {
driving = parseFloat(results[j].distance.text); // driving is a script wide variable to hold the return value
}
}
}
}
答案 0 :(得分:1)
将回调传递给calculateDistances()函数,您可以通过传递回调并在方法结束时使用callback()执行回调。为清晰起见,将您的功能称为其他功
var driving = 0;
calculateDistances(callbackFunction);
function calculateDistances(callback) {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
//set origin and destination points
origins: [origin],//, origin2],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback());
}
function callbackFunction(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
}
//etc
}