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