1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const degrees_to_radians = Math.PI / 180;
const sin = (degrees: number) => Math.sin(degrees * degrees_to_radians);
const cos = (degrees: number) => Math.cos(degrees * degrees_to_radians);
/** Compatible with GeoJSON */
type Coordinates = readonly [longitude: number, latitude: number];
/**
* Calculate the haversine distance between two points on a sphere.
* The coordinates take the form [longitude, latitude] in degrees.
* An default radius is the average Earth’s radius of 6371km.
*
* @see {https://en.wikipedia.org/wiki/Haversine_formula}
*/
export const haversine_distance = ([λ1, φ1]: Coordinates, [λ2, φ2]: Coordinates, radius = 6371) =>
2 * radius * Math.asin(Math.sqrt(sin((φ2 - φ1) / 2) ** 2 + cos(φ1) * cos(φ2) * sin((λ2 - λ1) / 2) ** 2));