Javascript 返回未定义值的回调函数
我正在尝试使用谷歌地图API返回从一个点到另一个点的旅程时间和长度。这是我的密码Javascript 返回未定义值的回调函数,javascript,callback,undefined,Javascript,Callback,Undefined,我正在尝试使用谷歌地图API返回从一个点到另一个点的旅程时间和长度。这是我的密码 var routeInfoObject; function findRoutes(given_origin, given_destination){ var directionsService = new google.maps.DirectionsService(); var directionsRequest = { origin: given_origin, destination
var routeInfoObject;
function findRoutes(given_origin, given_destination){
var directionsService = new google.maps.DirectionsService();
var directionsRequest = {
origin: given_origin,
destination: given_destination,
travelMode: google.maps.DirectionsTravelMode.WALKING,
unitSystem: google.maps.UnitSystem.METRIC,
provideRouteAlternatives: true
};
var times = new Array();
var lengths = new Array();
var positions = new Array();
directionsService.route(directionsRequest, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
for (i = 0; i < response.routes.length && i < 4 ; i++)
{
times[i] = response.routes[i].legs[0].duration.text;
lengths[i] = response.routes[i].legs[0].distance.text;
}
routeInfoObject = times;
} else {
console.log("There was an error with the request")
}
});
console.log(routeInfoObject);
}
var路由信息对象;
函数findurotes(给定源、给定目标){
var directionsService=new google.maps.directionsService();
变量方向请求={
产地:给定产地,
目的地:给定的目的地,
travelMode:google.maps.Directions travelMode.WALKING,
unitSystem:google.maps.unitSystem.METRIC,
ProviderRouteAlternatives:true
};
var times=新数组();
变量长度=新数组();
var positions=新数组();
路由(DirectionRequest,函数(响应,状态){
if(status==google.maps.directionstatus.OK){
对于(i=0;i
底部的日志始终返回undefined,即使RouteInfo对象是一个全局变量,并且应该设置为times值。如果我运行FindLotes(“longsight”、“rusholme”)将返回[18,18,18]。回调函数(
函数(响应,状态)
)直到您的控制台.log
语句之后才会执行,因此它还没有被赋值。我很困惑,如何解决这个问题?本质上,我需要从回调中返回一个值,然后再从findrootes函数中返回。@user2952231-通常不能使异步api同步运行;您需要将回调传递给FindRoots,告诉它们您以后要做什么,或者在RouteInfo对象不再未定义时执行setTimeout/interval wait和check。