为什么这个依赖于HTML5地理位置的javascript代码出错

Why is this HTML5 geolocation-dependent javascript code erring?

本文关键字:javascript 代码 出错 地理位置 HTML5 依赖于 为什么      更新时间:2023-09-26

我有一些javascript代码,具体取决于地理位置。

http://jsfiddle.net/8D6vz/

var myLat = 0.0;
var myLng = 0.0;
function setCurrentPosition(position) {
 myLat = position.coords.latitude;
 myLng = position.coords.longitude;
}
function errorOccured() {
 document.write("sorry, error occured :( ");
}
$(function() {
 navigator.geolocation.getCurrentPosition(setCurrentPosition, errorOccured);
 document.write(myLat + " " + myLng);
});

但是,此代码仅生成

0 0

而不是

"client's latitude here" "client's longitude here"

为什么?

我正在使用谷歌浏览器,它肯定支持地理位置。我还允许我的浏览器跟踪我的位置。​

GetCurrentPosition 是一个异步函数,你可以像这样使用它

function GetGeolocation() {
navigator.geolocation.getCurrentPosition(GetCoords, GetError);
}
function GetCoords(position){
  var lat = position.coords.latitude;
  var long = position.coords.longitude;
  var accuracy = position.coords.accuracy;
  alert('Latitude: ' + lat + ', Longitude: '+ long);
}

哦,我想我想通了。

我相信

navigator.geolocation.getCurrentPosition()

是一个异步函数。因此,在屏幕上打印纬度和经度值后调用setCurrentPosition(position),屏幕打印原始值。