UNPKG

geo-distances

Version:

A geographical distance calculator. Calculates distance between two points using haversine formula.

62 lines (49 loc) 1.73 kB
'use strict' let lib = require('./lib'), colors = require('colors'), distances = [], message = ' cannot be empty'; /** * Return distance between two co-ordinates point * * @param {String} filepath filepath in string * @param {Object} start starting point coordinate * @param {String} range of distances * @param {unit} unit unit of distance measurement * @returns {Object} */ let getDistances = (filepath, start, range, unit) => { let data = require(filepath), lat1 = start.latitude, lon1 = start.longitude; let log = ((index, type, message) => { if (type == 'error') { console.log(colors.red(`error: In data array ${index} object is empty`)) console.log(colors.red(`${type}: ${message}`)); process.exit() } }) /** * Check if Latitude or Longitude is empty or undefined * * @param {Number} index index of object in array * @param {String} type error or success * @param {Object} coordinate location coordinate * @returns {Object} */ let checkCoordinates = ((index, type, coordinate) => { if (coordinate.trim() === "" || coordinate === undefined) { log(index, 'error', type + message); } return coordinate; }) data.filter((obj, index) => { let lat2 = checkCoordinates( index, 'latitude', obj.latitude); let lon2 = checkCoordinates(index, 'longitude', obj.longitude); let distance = lib.distance(lat1, lon1, lat2, lon2, unit); if (distance <= range) { obj["distance"] = distance distances.push(obj); } }); return distances; } module.exports = getDistances;