javascript - 为什么这个 HTML5 地理位置相关的 javascript 代码会出错?

标签 javascript html geolocation w3c-geolocation

我有一些取决于地理位置的 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"

为什么?

我使用的是 Google Chrome,它肯定支持地理定位。我还允许我的浏览器跟踪我的位置。

最佳答案

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);

}

关于javascript - 为什么这个 HTML5 地理位置相关的 javascript 代码会出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9781515/

相关文章:

javascript - 多个 显示更多/显示更少

javascript - 当原型(prototype)在外部使用 $ 时,如何在 domready 内部使用 $ 进行 jQuery?

html - 覆盖父 div 的 z-index?

javascript - 更改显示属性将页面滚动到顶部

jquery - mpg/mpeg 音频文件持续时间 jquery

javascript - 禁用 Angular 中的选择?

javascript - 我有一个 php 文件,在里面的代码中有一个错误,我不知道如何修复它?以及在哪里添加其余代码

html - 在 iPad 中禁用位置服务时使用 phonegap 获取 GeoLocation

php - 我如何使用 CloudFlare 地理定位检测所有欧洲国家

javascript - 重置浏览器地理位置值