我有一个跟踪和记录跑步者位置的正在运行的应用程序,并将坐标保存到数组中,目前为止还不错。 我试图循环遍历这个数组,并计算总共行驶的距离。
代码:
var startPos;
var num;
var distance;
navigator.geolocation.getCurrentPosition(function (position) {
startPos = position;
});
//
watchID = navigator.geolocation.watchPosition(function (position) {
pathArr.push(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var latlng = new google.maps.LatLng(lat, lon);
var num = calculateDistance(startPos.coords.latitude,startPos.coords.longitude,
position.coords.latitude, position.coords.longitude);
distance = num;
},
function (positionError) {
$("#error").append("Error: " + positionError.message + "<br />");
}, {
enableHighAccuracy: true,
timeout: 30 * 1000
});
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;
}
我意识到的是,这个计算方式只在我沿着一条直线行走时才能正常工作,因为它总是从起点到当前点而不是逐一计算。如果跑步者回到零点,总距离将为0或接近于0,我需要改变它以便计算从坐标到坐标的距离并添加总距离。
我尝试了这个:
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var latlng = new google.maps.LatLng(lat, lon);
num += calculateDistance(startPos.coords.latitude, startPos.coords.longitude,
position.coords.latitude, position.coords.longitude);
startPos = latlng;
distance = num;
没有运气了。 请帮忙。