2014-03-26 19 views
0

我不明白爲什麼我會得到這個結果,我從來沒有能夠掌握JavaScript,因爲我總是被多麼不穩定的威脅所嚇倒代碼的行爲與Python或Java相比。JavaScript一直返回'undefined',控制檯日誌是完全正常的

我需要將變量lng_設置爲當前的經度,一旦我發現我會和lat_一樣。這裏是我的代碼:

var lng_ = navigator.geolocation.getCurrentPosition(GetLong); 
var lat_ = navigator.geolocation.getCurrentPosition(GetLat);  

function GetLong(location) 
{ 
    console.log(location.coords.longitude); 
    var ret = location.coords.longitude; 
    return ret; 
} 

console.log(lng_); 

function GetLat(location) 
{ 
    return(location.coords.latitude); 
} 

,如果你看一下function GetLong(location)它應該返回經度的價值,幷包括一個JavaScript記錄顯示,如果它的工作。

而且根據我的JavaScript的日誌,我得到正確的結果

-122.15616500000002

但是,當我在ret存儲這個值,並返回它,最終console.log()配備了undefined

JavaScript如何知道它返回的是什麼類型的對象,無論它是字符串還是int?我的問題有什麼解決方案?

+4

'navigator.geolocation.getCurrentPosition()'不返回任何東西。它將「返回值」傳遞給回調函數。 – Blender

+0

[如何從AJAX調用返回響應?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Bergi

回答

2

您只需使用回調函數調用getCurrentPosition()一次,調用時實際並不返回位置;原因是該位置不會立即可用:

function getPosition(location) 
{ 
    var lng_, lat_; 

    lng_ = location.coords.longitude; 
    lat_ = location.coords.latitude; 

    // do stuff with position here 
} 

navigator.geolocation.getCurrentPosition(GetPosition); 

它的工作原理與其他異步操作在JavaScript中的工作方式非常相似。

相關問題