2012-05-27 46 views
0

我對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」。有什麼辦法可以解決這個問題嗎?

+0

您可以使用jQuery AJAX調用並設置'async:false',這會讓您的程序等待,直到您想要加載的任何資源。 –

+0

你能告訴我一些樣品的鏈接嗎?我從來沒有用過這樣的東西。 – Martus0

+1

[函數返回前是否會等待異步函數完成?](可能是函數返回之前等待異步函數完成的重複嗎?)(http://stackoverflow.com/questions/6284457/will-the-function-wait-for-the-asynchronous-functions-completion-before -returnin)。 AJAX被稱爲* asynchronous *是有原因的。使其同步是一個壞主意。 – DCoder

回答

-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"); 
     } 
    }); 
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); 
}); 
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); 
} 
相關問題