Calculate distance between 2 geopoints

Calculating distance between GPS coordinates is something you’ll ALWAYS have to do on any geolocation-enabled application.

The most common use-case is to calculate the distance between the user’s current location and any other reference.

The TypeScript function ‘calculateDistance’ returns the distance in kilometers:


const calculateDistance = (
latitude1,
longitude1,
latitude2,
longitude2
) => {
//radians
const lat1 = (latitude1 * 2.0 * Math.PI) / 60.0 / 360.0;
const long1 = (longitude1 * 2.0 * Math.PI) / 60.0 / 360.0;
const lat2 = (latitude2 * 2.0 * Math.PI) / 60.0 / 360.0;
const long2 = (longitude2 * 2.0 * Math.PI) / 60.0 / 360.0;

// use to different earth axis length
const a = 6378137.0; // Earth Major Axis (WGS84) in meters
const b = 6356752.3142; // Minor Axis in meters
const f = (a - b) / a; // "Flattening"
const e = 2.0 * f - f * f; // "Eccentricity"

let beta = a / Math.sqrt(1.0 - e * Math.sin(lat1) * Math.sin(lat1));
let cos = Math.cos(lat1);
let x = beta * cos * Math.cos(long1);
let y = beta * cos * Math.sin(long1);
let z = beta * (1 - e) * Math.sin(lat1);

beta = a / Math.sqrt(1.0 - e * Math.sin(lat2) * Math.sin(lat2));
cos = Math.cos(lat2);
x -= beta * cos * Math.cos(long2);
y -= beta * cos * Math.sin(long2);
z -= beta * (1 - e) * Math.sin(lat2);
return Math.sqrt(x * x + y * y + z * z) / 1000;
};

Senior Full-stack Developer. Self-taught programmer since I was 11yo. Chemical Engineer specialized in Waste Water Bio-treatment and Process simulation and modeling. Major Geek.