我正在使用DirectionsService
课程向Google服务器发送API请求。并得到回应。但我无法将该响应分配给变量。
我尝试了以下方式它无法正常工作(未定义)。
var gettingApiresponce=function(sourcePlace,destinationPlace){
var directionService=new google.maps.DirectionsService();
var responce;
directionService.route(
{
origin:sourcePlace,
destination:destinationPlace,
travelMode:"DRIVING"
},function(res,status){
responce=res;
});
return responce;
};
我该如何解决这个问题。
答案 0 :(得分:0)
路线服务是异步的。任何使用响应的东西都应该在回调函数中运行(或之后)。因此,您无法“返回”结果。
// put in the global scope.
var responce;
var gettingApiresponce=function(sourcePlace,destinationPlace){
var directionService=new google.maps.DirectionsService();
directionService.route(
{
origin:sourcePlace,
destination:destinationPlace,
travelMode:"DRIVING"
},function(res,status){
//this will set the global variable responce, but anything that needs to be
// done with the returned value should be done here.
responce=res;
var directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setDirections(res);
directionsRenderer.setMap(map);
// etc.
});
// can't do this returns before the callback function runs.
//return responce;
};