I tried to calculate the distance between two coordinates in javascript.
More specifically the distance between one set of static coordinates and my current position taken from the geolocation cordova plugin.
Here's my code:
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
};
var onSuccess = function(position) {
document.getElementById("content").innerHTML = 'Success, attempting calculation...';
var lla = position.coords.latitude;
var llo = position.coords.longitude;
document.getElementById("content").innerHTML =
'GPS Position: ' + calcTheDistance(lla, llo).d + 'Metres';
};
var onError = function(error) {
document.getElementById("content").innerHTML =
'code: ' + error.code + '\n' +
'message: ' + error.message + '\n';
};
function refrGps() {
document.getElementById("content").innerHTML = 'Loading...';
navigator.geolocation.getCurrentPosition(onSuccess, onError);
};
function calcTheDistance(lati1, long1) {
var r = 6371000; //Meters
var joschLat = 50.1109221;
var joschLon = 8.6821267;
var la1 = lati1;
var la2 = joschLat;
var lat1 = lati1.toRadians();
var lat2 = joschLat.toRadians();
var lo1 = long1;
var lo2 = joschLon;
var la2minla1 = (la2-la1).toRadians();
var lo2minlo1 = (lo2-lo1).toRadians();
var cal = Math.sin(la2minla1 / 2) * Math.sin(la2minla1 / 2) +
Math.cos(lat1) * Math.cos(lat2) *
Math.sin(lo2minlo1/2) * Math.sin(lo2minlo1/2);
var c = 2* Math.atan2(Math.sqrt(cal), Math.sqrt(1-cal));
d = r * c;
};
I tried to rewrite it several times with no luck.
For the calculation I referred to this: http://www.movable-type.co.uk/scripts/latlong.html