问题描述
我对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返回结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!