-1

我正在使用DirectionsService类向谷歌服务器发送 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;
 };

我怎样才能解决这个问题。

4

1 回答 1

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;
 };
于 2013-11-07T15:45:11.607 回答