我有两个函数:getCoordinate()和getDistance(),都需要向google apis发出异步请求,结果是一个json文件,
获取距离:
function getDistance(origin,destination,mode)
{
var url="http://maps.googleapis.com/maps/api/distancematrix/json?";
var origin="origins="+origin;
var destination="&destinations="+destination;
var mode="&mode="+mode;
var language="&language=fr-FR"
var sensor="&sensor=false";
var def = new jQuery.Deferred();
var city;
$.getJSON(url+origin+destination+mode+language+sensor,function(json)
{
if (json.status=="OK")
{
var distance=json.rows[0].elements[0].distance.value;
}
def.resolve(distance);
});
return def.promise();
}
这是getCoordinates:
function getCoordinate(address)
{
var url="http://maps.googleapis.com/maps/api/geocode/json?address=";
var sensor="&sensor=false";
var def = new jQuery.Deferred();
var city;
$.getJSON(url+address+sensor,function(json)
{
var lat=json.results[0].geometry.location.lat;
var lng=json.results[0].geometry.location.lng;
var dist=google.maps.geometry.spherical.computeDistanceBetween(myCenter,new google.maps.LatLng(lat,lng));
console.log('address:'+dist/1000+'km');
var coord=[lat,lng];
def.resolve(coord);
});
return def.promise();
}
我需要在 getDistance() 中使用 getCoordinate() 方法的结果,但由于异步模式 getDistance 指令在结果从谷歌返回之前执行。
for (i=0;i<addresses.length;i++)
{
$.when(getCoordinate(addresses[i])).then(function (coord) {
var myLatitude=coord[0];
var myLongitude=coord[1];
addressList[j++]=[coord[0],coord[1]];
$.when(getDistance(lat+","+lng,myLatitude+","+myLongitude,"driving")).then(function(distance)
{
var test=i;
var distTab=[];
switch(i){
case 0:
//do Something
break;
default:
//do something
break;
}
}
});
});
} console.log("the dist:"+distance);
console.log("coordinate:"+myLatitude+","+myLongitude);
console.log("Center:"+lat+","+lng);