2014-11-16 26 views
1

以外的地方,變量返回爲undefined,所以我在過去的幾個小時裏一直有這個問題。我試圖通過使用導航器對象來獲取用戶的位置,並且我可以獲得經緯度,但是當我嘗試返回並將其用作Google地圖LatLng對象的變量時,它返回爲未定義。當navigator.geolocation.getCurrentPosition

下面是代碼:

function getCurrentLat(){ 
    var lat 
    if(navigator.geolocation){ 

     navigator.geolocation.getCurrentPosition(function(position) { 
      lat = position.coords.latitude; 
      alert(lat); 
     }); 
     alert(lat); 
    }else{ 
     console.log("Unable to access your geolocation"); 
    } 
    return lat; 
} 

的getCurrentPosition功能將顯示正確的緯度內的第一警報,但是,功能外,第二個顯示爲未定義。如何讓變量在getCurrentPosition()函數之外正確顯示?

+0

'return lat;'也許不是'return(lat);'......這是什麼意思? –

+0

哎呀,那是一個錯字。使用回報;不起作用。 – Ajax413

回答

0

getCurrentPosition需要一個回調函數,並且在這個函數中你最終得到一個不同的內部作用域(並且可能不會立即執行)。所以,你可以做到這一點的唯一方法是要麼返回未來,或在回調,如:

function getCurrentLat(callback){ 
    if(navigator.geolocation){ 

     navigator.geolocation.getCurrentPosition(function(position) { 
      callback(position.coords.latitude); 
     }); 
    }else{ 
     console.log("Unable to access your geolocation"); 
    } 
} 

否則,它很清楚爲什麼lat將是不確定的,因爲getCurrentPosition甚至不會有機會執行並在該函數退出之前調用回調函數。

+0

有道理,我認爲這是一個範圍問題,只是無法弄清楚如何通過它。對於回調函數,究竟傳遞給主getCurrentLat()函數的是什麼?對不起,我對回調有點新,所以我不能100%確定從上述回調中獲取價值的最佳方式是什麼。有沒有一種方法可以將getCurrentLat()的返回值設置爲position.coords.latitude? – Ajax413

+0

在這種情況下,它會傳遞'position.coords.latitude'的值。例如,類似'getCurrentLat(函數(緯度){alert('您的緯度是'+緯度);})' –

相關問題