I'm trying to code some JS that calculates the distance a user travels using the Haversine formula.
Now Haversine formula takes in the starting and current coordinates and gives out the separation between those two coordinates. That is however just the DISPLACEMENT and NOT the distance a user might have probably travelled to reach the final point.
I need someone to help me on the code I did below (that gives displacement) and suggest what should I do more so that it calculates distance.
//Geolocation
var startPos;
var watchId;
//Start Tracking Position
function startTracking() {
if(navigator.geolocation) {
if (document.getElementById('startBtn').innerHTML === " Stop Tracking?")
{
stopTracking();
stopClock();
return;
}
document.getElementById('startBtn').innerHTML = " Stop Tracking?";
//Get Position
navigator.geolocation.getCurrentPosition(showPosition, showError);
//Watch Position
watchId = navigator.geolocation.watchPosition(showPositionUpdate, showError);
}
else {
alert('Geolocation is not supported by your browser');
}
}
//Show Start Position
function showPosition(position) {
startPos = position;
document.getElementById('startLat').innerHTML = startPos.coords.latitude;
document.getElementById('startLon').innerHTML = startPos.coords.longitude;
}
//Updated Position
function showPositionUpdate(position) {
document.getElementById('currentLat').innerHTML = position.coords.latitude;
document.getElementById('currentLon').innerHTML = position.coords.longitude;
var distance = calculateDistance(startPos.coords.latitude, startPos.coords.longitude, position.coords.latitude, position.coords.longitude);
if (distance < 1) {
document.getElementById('distance').innerHTML = (Math.round(distance * 1000)) + "m";
} else {
document.getElementById('distance').innerHTML = (Math.round(distance * 100) / 100) + "Km";
}
}
//Error Handler
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
alert('User denied the request for Geolocation');
break;
case error.POSITION_UNAVAILABLE:
alert('Location Not Available');
break;
case error.TIMEOUT:
alert('The request has timed-out');
break;
case error.UNKNOWN_ERROR:
alert('There was an unknown error');
break;
}
}
//Calculate the distance between start and updated, Haversine Formula
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;
}
//Stop Tracking
function stopTracking() {
navigator.geolocation.clearWatch(watchId);
alert('Tracking has stopped');
document.getElementById('startBtn').innerHTML = "Start Tracking?";
}