I've developed a running app that keeps track of the runner's location and saves the coordinates into an array successfully. Now, I'm facing an issue where I need to loop over the array to calculate the total distance traveled.
Here is the code snippet:
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;
}
Upon testing, I noticed that the calculation only works accurately when walking in a straight line because it always measures from the starting point to the current one. If the runner circles back to the starting point, the total distance will be zero or close to it. To fix this, I attempted the following:
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;
However, this did not yield the expected results. Any assistance would be greatly appreciated.