gpt4 book ai didi

javascript - Chrome 中的地理定位 API : coord property of Position undefined

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

我正在 Google Chrome (v13) 中试用 Geolocation API。我制作了一个简单的 HTML 页面来掌握基础知识:

<html>
<head>
<script type="text/javascript">
navigator.geolocation.getCurrentPosition(doStuff, error, setOptions);

function setOptions(geoLoc) {
geoLoc.enableHighAccuracy = true;
geoLoc.timeout = 30;
geoLoc.maximumAge = 0;
}

function doStuff(geoLoc) {
document.getElementById("refreshTimestamp").innerHTML = "Last refresh: " + Date.now();
document.getElementById("latitude").innerHTML = "Latitude: " + geoLoc.coords.latitude;
document.getElementById("longitude").innerHTML = "Longitude: " + geoLoc.coords.longitude;
document.getElementById("altitude").innerHTML = "Altitude: " + geoLoc.coords.altitude;
document.getElementById("accuracy").innerHTML = "Accuracy: " + geoLoc.coords.accuracy;
document.getElementById("altitudeAccuracy").innerHTML = "Altitude Accuracy: " + geoLoc.coords.altitudeAccuracy;
document.getElementById("heading").innerHTML = "Heading: " + geoLoc.coords.heading;
document.getElementById("speed").innerHTML = "Speed: " + geoLoc.coords.speed;
}

function error(geoLoc) {
document.getElementById("error").innerHTML = "ERROR! Code: " + geoLoc.code + "; Message: " + geoLoc.message;
}
</script>
</head>
<body onload="doStuff()">
<p id="refreshTimestamp"></p>
<p id="latitude"></p>
<p id="longitude"></p>
<p id="altitude"></p>
<p id="accuracy"></p>
<p id="altitudeAccuracy"></p>
<p id="heading"></p>
<p id="speed"></p>
<p id="error"></p>
</body>
</html>

运行此页面,一切正常 - 纬度、经度和精度按预期显示。但是,查看 Developer Tools Console 时,出现错误:

Uncaught TypeError: Cannot read property 'coords' of undefined (geo.html:14)

调试看起来 Position 对象在第一次调用时未定义 - 处理纬度的行。然而,任何其他行都没有错误。事实上,在纬度线之后,Postition 对象就存在了。

我试图防止此错误的事情包括:

  1. 将 getCurrentPosition 调用移到回调函数声明之后
  2. 将 geoLoc.coords 分配给一个 XY 变量作为 doStuff() 函数的第一行(这样做之后,正是这部分代码导致了错误)

我是否错误地调用了 Position 对象?是 Chrome 怪癖吗?这与确定位置所花费的时间有关吗?

谢谢,克里斯。

最佳答案

它是未定义的,因为:

<body onload="doStuff()">

也许你想要这样的东西:

function init() {
navigator.geolocation.getCurrentPosition(doStuff, error, setOptions);
}
...
<body onload="init()">

关于javascript - Chrome 中的地理定位 API : coord property of Position undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7210193/

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