有什么方法可以等到DirectionsService返回结果? [英] Is there any way to wait until the DirectionsService returns results?

查看:166
本文介绍了有什么方法可以等到DirectionsService返回结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

pre $函数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 总是显示:undefined 。有没有什么办法可以解决这个问题?

解决方案

我不认为这是可能的。你可以在snap_to_road中使用一个回调参数:
$ b $ pre $ 函数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);
}
});

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


I have a problem with the Google DirectionsService. I know it's asynchronous and that is the cause of my troubles. I'd like to wait until the DirectionsService returns a result instead of executing code without an answer. Here is a sample:

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));

The alert always shows: "undefined". Is there any way to solve this?

解决方案

I don't think that is possible. You could use a callback parameter in 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);
});

这篇关于有什么方法可以等到DirectionsService返回结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆