Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@yblee85
Forked from mattpowell/distance.js
Created January 30, 2020 20:53
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 yblee85/cb3452e62cb01ee7f0e92f33e8b37b4b to your computer and use it in GitHub Desktop.
Save yblee85/cb3452e62cb01ee7f0e92f33e8b37b4b to your computer and use it in GitHub Desktop.
Get the distance between two (world) coordinates - a nodejs module
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* */
/* Simple node js module to get distance between two coordinates. */
/* */
/* Code transformed from Chris Veness example code - please refer to his website for licensing */
/* questions. */
/* */
/* */
/* Latitude/longitude spherical geodesy formulae & scripts (c) Chris Veness 2002-2011 */
/* - www.movable-type.co.uk/scripts/latlong.html */
/* */
/* */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/** Converts numeric degrees to radians */
if(typeof(Number.prototype.toRad) === "undefined") {
Number.prototype.toRad = function () {
return this * Math.PI / 180;
}
}
// start and end are objects with latitude and longitude
//decimals (default 2) is number of decimals in the output
//return is distance in kilometers.
exports.getDistance = function(start, end, decimals) {
decimals = decimals || 2;
var earthRadius = 6371; // km
lat1 = parseFloat(start.latitude);
lat2 = parseFloat(end.latitude);
lon1 = parseFloat(start.longitude);
lon2 = parseFloat(end.longitude);
var dLat = (lat2 - lat1).toRad();
var dLon = (lon2 - lon1).toRad();
var lat1 = lat1.toRad();
var lat2 = lat2.toRad();
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = earthRadius * c;
return Math.round(d * Math.pow(10, decimals)) / Math.pow(10, decimals);
};
{
"name": "distance.js",
"version": "0.0.1",
"description": "Util to calculate the distance between two sets of lat/long's. Originally cloned from https://gist.github.com/1604972.",
"main": "distance"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment