s-haversine
Version:
Get distance between any two latitute/longitude coordinates
56 lines (55 loc) • 1.89 kB
JavaScript
;
exports.__esModule = true;
/**
* Convert degrees to radians
*/
function degreesToRadians(deg) {
return deg * (Math.PI / 180);
}
exports.degreesToRadians = degreesToRadians;
/**
* Convert dms (degrees/minutes/seconds) string to decimal degrees
* toDecimal(`40 20 50W`) => -40.34722
* toDecimal(`40°20'50" S`) => -40.34722
*/
function dmsToDecimal(str) {
var lastChar = str.slice(-1).toLowerCase();
var negative = false;
// south and west => negative
if (lastChar === 'w' || lastChar === 's')
negative = true;
// convert strings to numbers
var values = str
.split(/[^0-9.]/)
.filter(function (x) { return x !== ''; }) // remove empty values
.map(function (x) { return parseFloat(x); });
// make sure array has length 3
for (var i = 0; i < 3; i++) {
values[i] = values[i] || 0;
}
var result = values[0] + (values[1] / 60) + (values[2] / 3600);
return negative ? -result : result;
}
exports.dmsToDecimal = dmsToDecimal;
var haversine = {
/**
* Configurable earthRadius (in meters)
*/
earthRadius: 6371000,
/**
* Get distance between two points
*/
distance: function (coords1, coords2) {
var lat1 = coords1[0], lon1 = coords1[1];
var lat2 = coords2[0], lon2 = coords2[1];
var latitudeDifference = degreesToRadians(lat2 - lat1);
var logitudeDifference = degreesToRadians(lon2 - lon1);
var n = Math.sin(latitudeDifference / 2) * Math.sin(latitudeDifference / 2) +
Math.cos(degreesToRadians(lat1)) * Math.cos(degreesToRadians(lat2)) *
Math.sin(logitudeDifference / 2) * Math.sin(logitudeDifference / 2);
var distance = 2 * Math.atan2(Math.sqrt(n), Math.sqrt(1 - n));
return this.earthRadius * distance;
},
dmsToDecimal: dmsToDecimal
};
exports["default"] = haversine;