如何使用:谷歌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()在初始化函數時調用窗體(窗口)加載時調用?
地理位置服務是異步的(因此位置將不會被定義,直到回調函數運行)。 [您的代碼張貼爲我工作](http://jsfiddle.net/pmmdg3cu/) – geocodezip
也許你是對的,我怎麼能告訴函數不會繼續除非getcurrentposition調用? –
您正在要求採取異步功能,這是異步的原因,並使其同步......研究/瞭解異步功能。 – geocodezip