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