-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
42 lines (36 loc) · 1.27 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
module.exports = {
/**
* Calculates the shortest distance from a starting point to multiple destinations.
* @param {object} _startingPoint The starting latitude and longitude.
* @param {array} options Array of destination options with latitude and longitude.
* @returns {object} The index and distance of the closest destination option.
*/
shortestDistance: (_startingPoint, _options) => {
let R = 3958.8; // Radius of earth calculated in miles
let shortest = {
index: 0,
distance: Number.MAX_VALUE,
};
const lat1 = _startingPoint.latitude;
const lon1 = _startingPoint.longitude;
_options.forEach((option, i) => {
const lat2 = option.latitude;
const lon2 = option.longitude;
let dLat = ((lat2 - lat1) * Math.PI) / 180;
let dLon = ((lon2 - lon1) * Math.PI) / 180;
let a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos((lat1 * Math.PI) / 180) *
Math.cos((lat2 * Math.PI) / 180) *
Math.sin(dLon / 2) *
Math.sin(dLon / 2);
let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
let d = R * c; // Distance in miles
if (d < shortest.distance) {
shortest.index = i;
shortest.distance = d;
}
});
return shortest;
},
};