Skip to content

Instantly share code, notes, and snippets.

@khriztianmoreno
Created September 4, 2017 15:47
Show Gist options
  • Save khriztianmoreno/83bdd2feeb92fbb3a5c2756021f94231 to your computer and use it in GitHub Desktop.
Save khriztianmoreno/83bdd2feeb92fbb3a5c2756021f94231 to your computer and use it in GitHub Desktop.
Distance between two geographical points
/**
* Source http://www.movable-type.co.uk/scripts/latlong.html
*/
const distanceBetween = (lat2, lat1, lng2, lng1) => {
Number.prototype.toRad = function() {
return this * Math.PI / 180;
};
// Haversine Formula
const x1 = lat2-lat1;
const dLat = x1.toRad();
const x2 = lng2-lng1;
const dLon = x2.toRad();
const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon/2) * Math.sin(dLon/2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
const distance = Math.round(((RADIUS * c) * FOOT) / 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment