UNPKG

calculate-distance-between-coordinates

Version:
56 lines (55 loc) 1.84 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getTotalDistance = exports.getDistanceBetweenTwoPoints = void 0; // source of algorithm: https://www.geodatasource.com/developers/javascript function getDistanceBetweenTwoPoints(cord1, cord2, unit) { if (unit === void 0) { unit = 'km'; } if (cord1.lat === cord2.lat && cord1.lon === cord2.lon) { return 0; } var radlat1 = (Math.PI * cord1.lat) / 180; var radlat2 = (Math.PI * cord2.lat) / 180; var theta = cord1.lon - cord2.lon; var radtheta = (Math.PI * theta) / 180; var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta); if (dist > 1) { dist = 1; } dist = Math.acos(dist); dist = (dist * 180) / Math.PI; dist = dist * 60 * 1.1515; if (unit === 'km') { dist = dist * 1.609344; } return dist; } exports.getDistanceBetweenTwoPoints = getDistanceBetweenTwoPoints; function getTotalDistance(coordinates, unit) { if (unit === void 0) { unit = 'km'; } coordinates = coordinates.filter(function (cord) { if (cord.lat && cord.lon) { return true; } }); var totalDistance = 0; if (!coordinates) { return 0; } if (coordinates.length < 2) { return 0; } for (var i = 0; i < coordinates.length - 2; i++) { if (!coordinates[i].lon || !coordinates[i].lat || !coordinates[i + 1].lon || !coordinates[i + 1].lat) { totalDistance = totalDistance; } totalDistance = totalDistance + getDistanceBetweenTwoPoints(coordinates[i], coordinates[i + 1], unit); } return totalDistance.toFixed(2); } exports.getTotalDistance = getTotalDistance;