问题
I have Two functions : getCoordinate() and getDistance(), both need to make asynchronous request to google apis, the result is a json file,
getDistance:
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();
}
And this is 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();
}
I need use the results of getCoordinate() method inside getDistance(), but due to the ansynchrous mode getDistance instructions are executed before the results come back from google.
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);
回答1:
As you are already using 'google.maps', there are advantages in passing all lat/lng values around as 'google.maps.LatLng' objects.
Also, variables are addressable only when in scope and only once assigned in an async callback, so some of your attempts to console.log() are bound to fail.
Applying these principles and tidying up (significantly), I get :
function getDistance(origin, destination, mode) {
//Note: //origin, destination are now google.maps.LatLng objects
var url = "http://maps.googleapis.com/maps/api/distancematrix/json";
var data = {
origin: origin.toUrlValue(),
destination: destination.toUrlValue(),
mode: mode,
language: "fr-FR",
sensor: "false"
};
return $.getJSON(url, data).then(function(json) {
if(json.status=="OK") {
return json.rows[0].elements[0].distance.value;
}
else return $.Deferred().reject().promise();
});
}
function getCoordinate(address) {
var url="http://maps.googleapis.com/maps/api/geocode/json";
var data = {
address: address,
sensor: "false"
};
return $.getJSON(url, data).then(function(json) {
if(json.results && json.results.length && json.results[0].geometry) {
var latLng = new google.maps.LatLng(
json.results[0].geometry.location.lat,
json.results[0].geometry.location.lng
);
console.log("Center: " + latLng.toString());
return latLng;
}
});
}
for (i=0; i<addresses.length; i++) {
getCoordinate(addresses[i]).then(function(latLng) {
console.log("coordinate: " + latLng.toString());
addressList[j++] = latLng;//now a google.maps.LatLng object
getDistance(myOrigin, latLng, "driving").then(function(distance) {
console.log("the dist:" + distance);
switch(i) {
case 0: /* do Something */ break;
default: /* do something */ break;
}
});
});
}
untested
Of course, this won't work straight out of the box because the rest of your code will need to be adapted to work with google.maps.LatLng objects, particularly the variable I have called myOrigin (previously lat and lng in some outer scope) and those in addressList.
回答2:
Call the second function on success of the first function
var getCoordinate() { //call initial function
$.ajax({
success: function(results) {
getDistance(results);//call second function with the results of the first call
}
});
};
来源:https://stackoverflow.com/questions/17845100/cant-wait-unitil-results-come-back-from-google-api