Skip to content

Instantly share code, notes, and snippets.

@talesluna-zz
Created July 30, 2021 01:01
Show Gist options
  • Save talesluna-zz/6f9c4fde5c91205f2514343aae0f93b6 to your computer and use it in GitHub Desktop.
Save talesluna-zz/6f9c4fde5c91205f2514343aae0f93b6 to your computer and use it in GitHub Desktop.
Haversine calc in TypeScript
export const haversine = (coordinates1: [number, number], coordinates2: [number, number]) => {
const [ lat1, lon1 ] = coordinates1;
const [ lat2, lon2 ] = coordinates2;
const radian = (value: number) => value * (Math.PI / 180);
const dLat = radian(lat2 - lat1);
const dLon = radian(lon2 - lon1);
const result = Math.sin(dLat / 2)
* Math.sin(dLat / 2)
+ Math.cos(radian(lat1))
* Math.cos(radian(lat2))
* Math.sin(dLon / 2)
* Math.sin(dLon / 2);
return Math.floor((6371 * (2 * Math.atan2(Math.sqrt(result), Math.sqrt(1 - result)))) * 100) / 100;
};
@talesluna-zz
Copy link
Author

Usage

const kmRatio = haversine([38.8976038, -77.036366], [55.753818, 37.6162696]); // 7821.84
console.info('From White House to Kremlin:', kmRatio);

Proof

https://www.movable-type.co.uk/scripts/latlong.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment