我對Google DirectionsService有問題。我知道這是異步的,這是我的麻煩的原因。我想等到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
總是顯示:「undefined」。有什麼辦法可以解決這個問題嗎?
您可以使用jQuery AJAX調用並設置'async:false',這會讓您的程序等待,直到您想要加載的任何資源。 –
你能告訴我一些樣品的鏈接嗎?我從來沒有用過這樣的東西。 – Martus0
[函數返回前是否會等待異步函數完成?](可能是函數返回之前等待異步函數完成的重複嗎?)(http://stackoverflow.com/questions/6284457/will-the-function-wait-for-the-asynchronous-functions-completion-before -returnin)。 AJAX被稱爲* asynchronous *是有原因的。使其同步是一個壞主意。 – DCoder