Skip to content

Instantly share code, notes, and snippets.

@matiasmicheletto
Created October 8, 2022 00:56
Show Gist options
  • Save matiasmicheletto/33833a9a0377bfc797faa5511706336a to your computer and use it in GitHub Desktop.
Save matiasmicheletto/33833a9a0377bfc797faa5511706336a to your computer and use it in GitHub Desktop.
Compute distance in km between two coordinates using the haversine formula
const haversine = (pos1, pos2) => {
// https://stackoverflow.com/questions/639695/how-to-convert-latitude-or-longitude-to-meters
const R = 6378.137; // Radius of Earth
const dLat = pos2.lat * Math.PI / 180 - pos1.lat * Math.PI / 180;
const dLon = pos2.lng * Math.PI / 180 - pos1.lng * Math.PI / 180;
const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(pos1.lat * Math.PI / 180) * Math.cos(pos2.lat * Math.PI / 180) *
Math.sin(dLon/2) * Math.sin(dLon/2);
return (R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment