Skip to content

Instantly share code, notes, and snippets.

@monkeymonk
Last active October 22, 2019 08:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monkeymonk/390061dd3281dac4971fc41336d61ceb to your computer and use it in GitHub Desktop.
Save monkeymonk/390061dd3281dac4971fc41336d61ceb to your computer and use it in GitHub Desktop.
JavaScript Distance Between Coordinates #javascript #map
/**
* Returns the distance bewteen 2 coordinates.
* @param {Object} from - Object with lat and lng
* @param {Object} to - Object with lat and lng
* @return {float}
*/
function distance(from, to) {
const {atan2, cos, sqrt, sin} = Math;
// @note - radius of the planet earth in meters
const R = 6378137;
const toRad = Math.PI / 180;
const dLat = (to.lat - from.lat) * toRad;
const dLng = (to.lng - from.lng) * toRad;
const a = sin(dLat / 2) * sin(dLat / 2) + cos(from.lat * toRad) * cos(from.lat * toRad) * sin(dLng / 2) * sin(dLng / 2);
const c = 2 * atan2(sqrt(a), sqrt(1 - a));
return R * c;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment