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:
// ONLINE-RUNNER:browser;
const RADIAN = Math.PI / 180.0;
const RADIUS = 6371; // earth radius in km (https://dirask.com/posts/Constants-Earth-radius-in-km-p2YMAD)
const DIAMETER = 2 * RADIUS;
const toRadians = (degrees) => {
return RADIAN * degrees;
};
// Calcultes distance from a to b points in km (a and b variables should be provided in radians).
//
const calculateDistance$1 = (a, b) => {
const dLat = b.lat - a.lat;
const dLon = b.lon - a.lon;
const aTmp = Math.sin(0.5 * dLat);
const bTmp = Math.sin(0.5 * dLon);
const cTmp = aTmp * aTmp + bTmp * bTmp * Math.cos(a.lat) * Math.cos(b.lat);
return DIAMETER * Math.atan2(Math.sqrt(cTmp), Math.sqrt(1.0 - cTmp));
};
// Calcultes distance from a to b points in km (a and b variables should be provided in degrees).
//
const calculateDistance$2 = (a, b) => {
const aTmp = {lat: toRadians(a.lat), lon: toRadians(a.lon)};
const bTmp = {lat: toRadians(b.lat), lon: toRadians(b.lon)};
return calculateDistance$1(aTmp, bTmp);
};
// Usage example:
const a = {lat: 51.5283080, lon: -0.3817765}; // London City (United Kingdom)
const b = {lat: 40.6974034, lon: -74.1197612}; // New York City (USA)
const distance = calculateDistance$2(a, b);
console.log(distance); // ~5561.352931973071 [km]