Skip to content

Instantly share code, notes, and snippets.

@aflansburg
Created April 6, 2021 19:03
Show Gist options
  • Save aflansburg/83f08aff1565e01f0e87099d5a24b021 to your computer and use it in GitHub Desktop.
Save aflansburg/83f08aff1565e01f0e87099d5a24b021 to your computer and use it in GitHub Desktop.
Haversine - Straight Line Distance Between Two Sets of Geographical Coordinates (Latitude, Longitude)
// see the Haversine formula description here
// https://community.esri.com/t5/coordinate-reference-systems/distance-on-a-sphere-the-haversine-formula/ba-p/902128
function haversine(coord1, coord2){
// radius of earth in meters
const R = 6371000;
// convert latitude degrees to radians
const phi_1 = Math.radians(coord1.latitude);
const phi_2 = Math.radians(coord2.latitude);
// delta being the "difference" between the latitudes and longitudes of each coordinate set expressed
// in radians
const delta_phi = Math.radians(coord2.latitude - coord1.latitude);
const delta_lambda = Math.radians(coord2.longitude - coord1.longitude);
// sin²(φB - φA/2) + cos φA * cos φB * sin²(λB - λA/2)
const a = Math.sin(delta_phi/2.0)**2 + Math.cos(phi_1) * Math.cos(phi_2) * Math.sin(delta_lambda/2.0)**2;
// 2 * atan2( √a, √(1−a) )
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
const meters = R * c;
const kilometers = meters / 1000.0;
const miles = kilometers / 1.609344;
return { meters, kilometers, miles};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment