我混合使用了W3C地理位置示例和HTML5rocks提供的示例,并尝试制作一个小的HTML5应用程序,该应用程序跟踪行进的距离。我使用以下代码:
...
<!DOCTYPE html>
<html>
<body>
<p>Click button to track your trip.</p>
<button onclick="getLocation()">Start Tracking</button>
<div id="startLat"></div><p />
<div id="startLon"></div><p />
<div id="distance"></div>
<script>
function getLocation() {
var distance_tmp;
if (navigator.geolocation) {
var startPos;
navigator.geolocation.getCurrentPosition(function(position) {
startPos = position;
document.getElementById('startLat').innerHTML = "Start Latitude: " + startPos.coords.latitude;
document.getElementById('startLon').innerHTML = "Start Longitude: " + startPos.coords.longitude;
});
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
navigator.geolocation.watchPosition(function(position) {
distance_tmp = calculateDistance(startPos.coords.latitude, startPos.coords.longitude,
position.coords.latitude, position.coords.longitude);
distance_tmp = Math.round((distance_tmp + Number.EPSILON) * 100) / 100;
document.getElementById('distance').innerHTML = distance_tmp + " km";
});
}
function calculateDistance(lat1, lon1, lat2, lon2) {
var R = 6371; // km
var dLat = (lat2 - lat1).toRad();
var dLon = (lon2 - lon1).toRad();
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
}
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
</script>
</body>
</html>
...
该脚本显然可以计算出我的起始位置和实际位置之间的距离,并且到目前为止效果很好。但是,例如,如果您围成一圈跑步,则距离越接近起始位置,距离就会减小。
我如何测量实际距离,以便即使我绕圈跑也能显示实际距离?我以为我可以总结不同的临时距离,但出现NaN错误。
非常感谢您。