|
| 1 | +/* |
| 2 | + Calculate the distance between two coordinates using the haversine formula |
| 3 | + More about: https://pt.wikipedia.org/wiki/F%C3%B3rmula_de_Haversine |
| 4 | + @Param {number} latitude1 |
| 5 | + @Param {number} latitude2 |
| 6 | + @Param {number} longitude1 |
| 7 | + @Param {number} longitude2 |
| 8 | + */ |
| 9 | +const haversineDistance = (latitude1 = 0, longitude1 = 0, latitude2 = 0, longitude2 = 0) => { |
| 10 | + validateLatOrLong(latitude1) |
| 11 | + validateLatOrLong(latitude2) |
| 12 | + validateLatOrLong(longitude1) |
| 13 | + validateLatOrLong(longitude2) |
| 14 | + const earthRadius = 6371e3 // 6,371km |
| 15 | + const pi = Math.PI |
| 16 | + const cos1 = latitude1 * pi / 180.0 |
| 17 | + const cos2 = latitude2 * pi / 180.0 |
| 18 | + const deltaLatitude = (latitude2 - latitude1) * pi / 180.0 |
| 19 | + const deltaLongitude = (longitude2 - longitude1) * pi / 180.0 |
| 20 | + |
| 21 | + const alpha = Math.sin(deltaLatitude / 2) * Math.sin(deltaLatitude / 2) + Math.cos(cos1) * Math.cos(cos2) * Math.sin(deltaLongitude / 2) * Math.sin(deltaLongitude / 2) |
| 22 | + const constant = 2 * Math.atan2(Math.sqrt(alpha), Math.sqrt(1 - alpha)) |
| 23 | + return earthRadius * constant |
| 24 | +} |
| 25 | + |
| 26 | +const validateLatOrLong = value => { |
| 27 | + if (typeof value !== 'number') { |
| 28 | + throw new TypeError('The value of latitude or longitude should be a number') |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +export { haversineDistance } |
0 commit comments