有没有办法等到DirectionsService返回结果?

时间:2012-05-27 13:35:29

标签: javascript google-maps-api-3 google-direction

我对Google DirectionsService有疑问。我知道它是异步的,这是我的麻烦的原因。我想等到DirectionsService返回结果,而不是在没有答案的情况下执行代码。这是一个示例:

function snap_to_road (lat) {
    var position;

    var request = {
        origin: lat,
        destination: lat,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            return response.routes[0].legs[0].start_location;
        }
    });
}

alert(snap_to_road(current.latLng));

alert始终显示:“未定义”。有什么方法可以解决这个问题吗?

4 个答案:

答案 0 :(得分:3)

我认为这是不可能的。您可以在snap_to_road中使用回调参数:

function snap_to_road (lat, callback) {
    var position;

    var request = {
        origin: lat,
        destination: lat,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            callback(response.routes[0].legs[0].start_location);
        }
    });
}

snap_to_road(current.latLng, function(result) {
    alert(result);
});

答案 1 :(得分:0)

在google指向返回结果后调用您的提醒方法。喜欢: 按钮点击事件后调用snap_to_road。

function snap_to_road (lat) {
  var position;

  var request = {
    origin: lat,
    destination: lat,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };

  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      ShowAlert(response.routes[0].legs[0].start_location);
    }
  });
}

function ShowAlert(result){
  alert(result);
}

答案 2 :(得分:0)

您可以让 snap_to_road() 返回一个 Promise,然后在异步函数中使用 await。 await 运算符用于等待 Promise。它只能在常规 JavaScript 代码中的异步函数内使用。像这样:

 function snap_to_road (lat) {
var position;

var request = {
    origin: lat,
    destination: lat,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
};
return new Promise((resolve, reject) => {
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            resolve(response.routes[0].legs[0].start_location);
        }else{
            reject(0);
        }
    });
});

}

async function alertPromise(){
    await snap_to_road(current.latLng).then((resolve) => {
        alert(resolve)
    })
}

你可以在reject()中放入一些消息并在之前处理。

答案 3 :(得分:-2)

这是我上面提到的一个例子:

var path = "/path/to/some/resource";

$.ajax({
        url:    path,
        type: "get",
        data: serializedData,  //<-- depends on what data you are using
        async: false, //will wait until resource has loaded or failed 

         //will be called on success
        success: function(response, textStatus, jqXHR){
            // log a message to the console
            console.log("Successfully loaded resource!");
        },
         //will be called on error
        error: function(jqXHR, textStatus, errorThrown){
            // log the error to the console
            console.log(
                "The following error occured: "+
                textStatus, errorThrown
            );
        },
        // callback handler that will be called on completion
        // which means, either on success or error
        complete: function(){
            console.log("Completed: with error or success");
        }
    });