Skip to content

Instantly share code, notes, and snippets.

@RomiC
Created September 13, 2019 07:35
Show Gist options
  • Save RomiC/d8db4d58782a6b6dcf2e6b036f3461f9 to your computer and use it in GitHub Desktop.
Save RomiC/d8db4d58782a6b6dcf2e6b036f3461f9 to your computer and use it in GitHub Desktop.
Calc the distance in meters between two geo-points
function distance(p1, p2) {
// radius of the sphere (Earth) in meters
const rad = 6372795;
// coordinates of two points
const {lat: llat1, long: llong1} = p1;
const {lat: llat2, long: llong2} = p2;
// in radians
const lat1 = llat1 * Math.PI / 180;
const lat2 = llat2 * Math.PI / 180;
const long1 = llong1 * Math.PI / 180;
const long2 = llong2 * Math.PI / 180;
// cosines and sines of latitudes and longitude differences
const cl1 = Math.cos(lat1);
const cl2 = Math.cos(lat2);
const sl1 = Math.sin(lat1);
const sl2 = Math.sin(lat2);
const delta = long2 - long1;
const cdelta = Math.cos(delta);
const sdelta = Math.sin(delta);
// calculating the length of a large circle
const y = Math.sqrt(Math.pow(cl2 * sdelta, 2) + Math.pow(cl1 * sl2 - sl1 * cl2 * cdelta, 2));
const x = sl1 * sl2 + cl1 * cl2 * cdelta;
const ad = Math.atan2(y, x);
const dist = ad * rad;
return dist; // in meters
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment