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

Mar*_*us0 0 javascript google-maps-api-3 google-directions-api

我在使用 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));
Run Code Online (Sandbox Code Playgroud)

alert始终表示:“未定义”。有没有办法解决这个问题?

Rob*_*Rob 5

我不认为这是可能的。您可以在 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);
});
Run Code Online (Sandbox Code Playgroud)