2012-09-27 25 views
0

我正在處理地理位置腳本,但無法獲取我的函數的內容。從javascript中的地理位置獲取數據

有人能幫助我嗎?

的代碼如下所示:

<script type="text/javascript"> 
var myvalue1; 
navigator.geolocation.getCurrentPosition(function() 
{ 
    myvalue1 = 'test'; 
    window.myvalue2 = 'demo'; 
}); 

console.log(myvalue1); 
console.log(window.myvalue2); 
</script> 

都返回undefined和我簡單不知道如何提取數據。

希望有人能幫助我。

在此先感謝。

+2

它是一個異步調用。 'console.log(myvalue1);'這行在myvalue1 ='test''之前被調用,只有當用戶允許共享權限時纔會調用該函數。因爲'myvalue1'最初是'undefined',它反映的是相同的 – Jashwant

回答

0

這是異步調用。試試這個

<script type="text/javascript"> 
var myvalue1; 
navigator.geolocation.getCurrentPosition(function() 
{ 
    myvalue1 = 'test'; 
    window.myvalue2 = 'demo'; 
    console.log(myvalue1); 
    console.log(window.myvalue2); 
}); 


</script> 
0

我認爲你的getCurrentPosition沒有被調用。將其放置在文檔就緒事件中。

0

試試這個:

<script type="text/javascript"> 

var coords; 

function outputPosition() 
{ 
    console.log('(' + coords.latitude + ', ' + coords.longitude + ')'); 
} 

navigator.geolocation.getCurrentPosition(function(position) 
{ 
    coords = position.coords; 
    outputPosition(); 
}); 

/* 
    coords will still be undefined here because the callback function 
    for getCurrentPosition has not been called yet. 
*/ 

</script> 
+0

是的,我知道這一點。問題是我真的需要功能以外的信息。 – user1645908

+0

我更新了我的代碼。在異步調用回調之前,不會分配「coords」。您可以通過調用另一個函數來訪問函數之外的信息。 – Andrew

+0

是的,我可以用這種製作功能的方式來製作一個很好的解決方案。感謝:D – user1645908