2017-03-22 66 views
0

控制檯日誌記錄lat返回undefined,而我想爲它指定position.coords.latitude的值。問題是什麼?如何在Javascript中爲異步函數內部分配全局變量?

$(document).ready(function(){ 
 
    var lat, lon; 
 

 
    if (navigator.geolocation) { 
 
    navigator.geolocation.getCurrentPosition(function(position) { 
 
     lat=position.coords.latitude; 
 
     lon=position.coords.longitude; 
 
    }); 
 
    console.log(lat); 
 
    } 
 
});  
 

+0

mayb e'navigator.geolocation.getCurrentPosition'不會發生。創建一個'else'的情況,並檢查。 – vaso123

+0

你有沒有嘗試把'console.log'放在'navigator.geolocation.getCurrentPosition'裏面? – Chinito

+0

'lat = position.coords.latitude;'這條線路不工作 –

回答

0

您無法登錄那裏,你必須需要回調函數來實現自己的目標

<script> 
    var x = document.getElementById("demo"); 
    function getLocation() { 
    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(showPosition); 
    } else { 
     x.innerHTML = "Geolocation is not supported by this browser."; 
    } 
} 
function showPosition(position) { 
    console.log("Latitude: " + position.coords.latitude +" Longitude: "   + position.coords.longitude) 
    x.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude; 
} 
</script> 
+0

雖然我從閱讀代碼中學到了一些東西,但它並不回答我的問題。我想獲得** position.coords.latitude **的價值 –

+0

以外您可以這樣做只有功能showPosition(position){ lat = position.coords.latitude; } –

+0

只有在回調函數中才能爲全局變量賦值 –

0

使用回調函數 $(文件)。就緒(函數() { var lat,lon;

if (navigator.geolocation) { 
    navigator.geolocation.getCurrentPosition(function(position) { 
     lat=position.coords.latitude; 
     lon=position.coords.longitude; 
     callbackFunction(); 
    }); 
    } 

    function callbackFuncton(){ 
     console.log(lat); 
     //you can use your lat and lon here 
    } 
});  
相關問題