@hyperbytes/wappler-distanmce-between-2-points
Version:
Calculate distance between two points, in miles, km or nautical miles
38 lines (27 loc) • 1.1 kB
JavaScript
// JavaScript Document
exports.distance = function (options) {
options = this.parse(options);
//units = units.toUpperCase();
let distanceunits = (options.dunits == 'M') ? 0.62137 : (options.dunits == 'N') ? 0.539957 : 1;
function toRad(v) { return v * Math.PI / 180; }
function kmToMiles(km) { return (km * distanceunits).toFixed(2); }
var l1 = LatLong(options.lat1, options.lon1);
var l2 = LatLong(options.lat2, options.lon2);
function LatLong(lat, lon) {
return { Latitude: lat, Longitude: lon }
}
function haversine(l1, l2) {
var R = 6371; // km
var x1 = l2.Latitude - l1.Latitude;
var dLat = toRad(x1);
var x2 = l2.Longitude - l1.Longitude;
var dLon = toRad(x2);
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(toRad(l1.Latitude)) * Math.cos(toRad(l2.Latitude)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
}
return kmToMiles(haversine(l1, l2));
}