Skip to content

Instantly share code, notes, and snippets.

@kawanet
Last active March 24, 2022 09:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kawanet/15c5a260ca3b98bd080bb87cdae57230 to your computer and use it in GitHub Desktop.
Save kawanet/15c5a260ca3b98bd080bb87cdae57230 to your computer and use it in GitHub Desktop.
calculate distance in kilometers between two points specified by degrees of latitude and longitude
/**
* calculate distance in kilometers between two points specified by degrees of latitude and longitude
*
* @author @kawanet
* @license MIT
* @see https://gist.github.com/kawanet/15c5a260ca3b98bd080bb87cdae57230
* @param {number} lat1 - degree of latitude of origin
* @param {number} lng1 - degree of longitude of origin
* @param {number} lat2 - degree of latitude of destination
* @param {number} lng2 - degree of longitude of destination
* @return {number} distance in kilometers between origin and destination
*/
function distance(lat1, lng1, lat2, lng2) {
lat1 *= Math.PI / 180;
lng1 *= Math.PI / 180;
lat2 *= Math.PI / 180;
lng2 *= Math.PI / 180;
return 6371 * Math.acos(Math.cos(lat1) * Math.cos(lat2) * Math.cos(lng2 - lng1) + Math.sin(lat1) * Math.sin(lat2));
}
if ("undefined" !== exports) exports.distance = distance;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment