2011-11-15 24 views
0

我得到了一些問題如何保存navigator.geolocation.getCurrentPosition的結果?

我想得到我目前的位置,並與它做一些事情。我用navigator.geolocation.getCurrentPosition功能如下:

$(document).ready(function(){ 
    var current_location; 
    navigator.geolocation.getCurrentPosition(function(position) { 
     current_location = position; 
    }); 

    // do something with current_location 
}); 

,但我不能分配給possition CURRENT_LOCATION。怎麼了?你可以告訴我如何將位置值分配給變量,以便將其用於navigator.geolocation.getCurrentPosition作用域?

感謝烏拉圭回合的幫助

P/S:我的英語不是很好:)

回答

2

使用此代碼工作,地理位置

if (navigator.geolocation) { 
    // geolocation is available 
    navigator.geolocation.getCurrentPosition(function(position) { 
     do_something(position);  
    }); 

    function do_something(position){ 
     // use position.coords.latitude, position.coords.longitude there 
     console.log(position); 
    } 
} 
+0

但我想保存的位置值(如一個對象),以便在navigator.geolocation.getCurrentPosition作用域之外的任何位置使用它。例如,如果我可以將位置指定給current_location,我可以訪問current_location.address.country以在視圖(MVC模式)中顯示國家 – Rocky

+0

我編輯了我的代碼,請檢查。在你的變體中,你不能將位置分配給current_location,因爲JavaScript--異步語言:)並且當下面的代碼執行current_location時,將執行current_location,而不會分配current_location。使用回調函數(do_something在我的代碼中) – fliptheweb

+0

非常感謝, – Rocky