From 4c77c8435dfaaaab8233c006d0ba29518517bcda Mon Sep 17 00:00:00 2001 From: Christian Weimann Date: Sat, 14 Oct 2023 05:27:23 +0200 Subject: [PATCH] First commit of distanceFrom function --- utils/lib.js | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/utils/lib.js b/utils/lib.js index d1cd070..1986aff 100644 --- a/utils/lib.js +++ b/utils/lib.js @@ -96,8 +96,36 @@ function convertValue(value) { } } +function distanceFrom(locationA, locationB) { + console.debug(`Calculate distance between ${locationA} and ${locationB}`); + + let lat1 = (locationA.split(',')[0]) * (Math.PI / 180); + let lon1 = (locationA.split(',')[1]) * (Math.PI / 180); + let lat2 = (locationB.split(',')[0]) * (Math.PI / 180); + let lon2 = (locationB.split(',')[1]) * (Math.PI / 180); + + if ((lat1 == lat2) && (lon1 == lon2)) { + return 0; + } + + // Haversine formula + let dlon = lon2 - lon1; + let dlat = lat2 - lat1; + let a = Math.pow(Math.sin(dlat / 2), 2) + + Math.cos(lat1) * Math.cos(lat2) + * Math.pow(Math.sin(dlon / 2),2); + let c = 2 * Math.asin(Math.sqrt(a)); + + // Radius of earth in meters + let r = 6371000; + + // calculate the result + return `${(c * r).toFixed()} m`; +} + module.exports = { compare, - convertValue + convertValue, + distanceFrom }; \ No newline at end of file