Languages
[Edit]
EN

JavaScript - distance between points on the Earth in km

6 points
Created by:
Mariam-Barron
841

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 format 51°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]

 

See also

  1. Constants - Earth radius in km

  2. JavaScript - convert longitude and latitude from degrees, minutes, and seconds (DMS) to decimal degrees (DD)

Alternative titles

  1. JavaScript - distance between coordinates on the Earth in km
  2. JavaScript - distance between coords on the Earth in km
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join