2013-04-10 60 views
0

我堅持這樣的問題:我想檢索根據地理位置,以便使用它在我的calcRoute功能作爲起點,例如定義的位置,這裏是代碼:如何檢索本地變量(地理位置HTML5和Google Maps API)?

function calcRoute(){ 
    var pos; 

    navigator.geolocation.getCurrentPosition 
    (
     function(position) 
     { 
      pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude); 
     } 
    ); 

    var start = pos; 
    alert(start); // pb here : start is undefined, how could I get the pos value ? 
    //... 
} 

非常感謝您的幫助!

+0

試着添加一個setTimeout,因爲匿名函數是由另一個線程執行的,並且你試圖在設置之前得到pos值。 – Pouki 2013-04-10 09:14:09

+0

不,請嘗試瞭解異步調用和使用回調是如何工作的。希望結果可能在那時使用setTimeout是相當無稽之談。 – CBroe 2013-04-10 09:20:46

回答

2

您定義的函數是一個回調函數,一旦檢索到位置就會調用該函數。

它會失敗的原因有兩個:

  • 你不知道,如果回調函數將被調用,不 的calcRoute其餘部分之前說的(實際上是因爲它非常 不可能是異步的)
  • 即使它在calcRoute的末尾 之前被調用,pos處於不同的範圍,因此您不能通過這種方式更改它 。

您可能會想借助全局變量來解決第二個問題,但是您將無法修復第一個問題。爲什麼不把你的代碼的其餘部分放在回調函數中?

function calcRoute(){ 
    navigator.geolocation.getCurrentPosition 
    (
     function(position) 
     { 
      var pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude); 
      var start = pos; 
      alert(start); 
     } 
); 

}

編輯:更詳細的回答解釋爲什麼要走這條路

0
function calcRoute(){ 
var pos; 

navigator.geolocation.getCurrentPosition 
(
    function(position) 
    { 
     pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude); 
     var start = pos; 
     alert(start); 
    } 
); 


//... 
} 
0

由於它是將以後執行的回調。但你可以分開你的代碼並讓它執行。

function calcRoute(){ 

    navigator.geolocation.getCurrentPosition 
    (
     function(position) 
     { 
      var pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude); 
      furtherCode(pos); 
     } 
    ); 

    } 

function furtherCode(position){ 
    var start = pos; 
    alert(start); 
    //... 
}