gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:30:29 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com