EN
TypeScript - distance between points on the Earth in km
0 points
In this short article, we would like to show how to calculate the distance in km between two points on the Earth using TypeScript.
Quick solution:
xxxxxxxxxx
1
interface Coordinates {
2
lat: number;
3
lon: number;
4
}
5
6
const RADIAN: number = Math.PI / 180.0;
7
const RADIUS: number = 6371; // earth radius in km (https://dirask.com/posts/Constants-Earth-radius-in-km-p2YMAD)
8
const DIAMETER: number = 2 * RADIUS;
9
10
const toRadians = (degrees: number): number => {
11
return RADIAN * degrees;
12
};
13
14
// Calcultes distance from a to b points in km (a and b variables should be provided in radians).
15
//
16
const calculateDistance$1 = (a: Coordinates, b: Coordinates): number => {
17
const dLat = b.lat - a.lat;
18
const dLon = b.lon - a.lon;
19
const aTmp = Math.sin(0.5 * dLat);
20
const bTmp = Math.sin(0.5 * dLon);
21
const cTmp = aTmp * aTmp + bTmp * bTmp * Math.cos(a.lat) * Math.cos(b.lat);
22
return DIAMETER * Math.atan2(Math.sqrt(cTmp), Math.sqrt(1.0 - cTmp));
23
};
24
25
// Calcultes distance from a to b points in km (a and b variables should be provided in degrees).
26
//
27
const calculateDistance$2 = (a: Coordinates, b: Coordinates): number => {
28
const aTmp = { lat: toRadians(a.lat), lon: toRadians(a.lon) };
29
const bTmp = { lat: toRadians(b.lat), lon: toRadians(b.lon) };
30
return calculateDistance$1(aTmp, bTmp);
31
};
32
33
34
// Usage example:
35
36
const a: Coordinates = { lat: 51.528308, lon: -0.3817765 }; // London City (United Kingdom)
37
const b: Coordinates = { lat: 40.6974034, lon: -74.1197612 }; // New York City (USA)
38
39
const distance: number = calculateDistance$2(a, b);
40
41
console.log(distance); // ~5561.352931973071 [km]
Output:
xxxxxxxxxx
1
5561.352931973071