2015-01-12 207 views
1

如何使用:谷歌Javascript地圖getCurrentPosition

navigator.geolocation.getCurrentPosition() 

來獲得當前位置的座標。
這是從谷歌網站上的例子:

function initialize() { 
var mapOptions = { 
    zoom: 6 
}; 
map = new google.maps.Map(document.getElementById('map-canvas'), 
    mapOptions); 

// Try HTML5 geolocation 
if(navigator.geolocation) { 
    navigator.geolocation.getCurrentPosition(function(position) { 
     var pos = new google.maps.LatLng(position.coords.latitude, 
            position.coords.longitude); 

     var infowindow = new google.maps.InfoWindow({ 
      map: map, 
      position: pos, 
      content: 'Location found using HTML5.' 
      }); 
     map.setCenter(pos); 
     }, function() { 
      handleNoGeolocation(true); 
     }); 
} else { 
    // Browser doesn't support Geolocation 
     handleNoGeolocation(false); 
} 
} 

我試着更換VAR POS部分myPos這是一個全局變量,但沒有奏效。
我的意思是我總是得到myPos initialize()函數後未定義。
獲取緯度和經度的正確方法是什麼navigator.geolocation.getCurrentPosition()在初始化函數時調用窗體(窗口)加載時調用?

+0

地理位置服務是異步的(因此位置將不會被定義,直到回調函數運行)。 [您的代碼張貼爲我工作](http://jsfiddle.net/pmmdg3cu/) – geocodezip

+0

也許你是對的,我怎麼能告訴函數不會繼續除非getcurrentposition調用? –

+0

您正在要求採取異步功能,這是異步的原因,並使其同步......研究/瞭解異步功能。 – geocodezip

回答

1

.getCurrentPosition()是一個異步函數,所以它需要一個回調,一旦它具有這些座標就執行,例如,

navigator.geolocation.getCurrentPosition(function(position){ 
    console.log(position); 
}); 

,這將給你這樣的事情:

{ 
    "timestamp": 1421093714138, 
    "coords": 
    { 
     "speed": null, 
     "heading": null, 
     "altitudeAccuracy": null, 
     "accuracy": 20, 
     "altitude": null, 
     "longitude": -122.4091036, 
     "latitude": 37.7837543 
    } 
} 

回調內部傳遞.getCurrentPosition你甚至可以更新變量,假定他們事先聲明。我猜你的myPos變量未定義的原因是因爲您連接到Google地圖API的方式存在問題。如果你不使用谷歌地圖,而只是想獲得一個位置,你可以做這樣的事情:

var myPos; 

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

哦,請確認您允許網站訪問您的位置。在Chrome中,你會得到你頁面的頂部的一欄寫着「<網站的網址>要使用您的計算機的位置[拒絕] [允許]」

編輯:

兩個錯誤。您只能在回調函數的範圍內訪問該變量 - 只有該函數運行後纔會定義tmpPos。正如我上面所說,.getCurrentPosition是一個asynchronous函數。這意味着它建立了一個過程來獲取您的地理位置,但同時還會執行其他任務(在您的情況下,它將繼續嘗試將其他變量更新爲尚未擁有的信息)。

另外,你在調用自己內部的初始化函數,這樣就會創建一個永無止境的無限循環函數。要解決此問題,請嘗試:

function initialize(){ 
navigator.geolocation.getCurrentPosition(function(position){ 
    // create the map here, because we only have access to position inside of this function 
    // even if we store in a global variable, it only gets updated once this callback runs 

    var currentPosition = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); 
} 

initialize(); 
+0

我現在在myPos中得到一個Geoposition對象,但是如果我嘗試訪問使用myPos.coords.latitude的實例緯度,我得到了異常:「Uncaught TypeError:無法讀取未定義的屬性'coords',雖然如果我打開變量有coords部分,我可以看到經度和緯度的數字。請參見[http://i61.tinypic.com/21l72o6.png] –

+0

有幾件事情是錯誤的。更新了我的答案。檢查這個資源(javascriptissexy.com/understand-javascript-callback-functions-and-use-them/)回調,我認爲這將有助於你對異步JS編碼模式的一般理解 –

+0

是啊謝謝,現在我明白了。 –