Skip to content

Commit ca45094

Browse files
committed
Added the Haversine distance algoritm
1 parent 0dfb200 commit ca45094

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

Navigation/Haversine.js

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
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 }

Navigation/Haversine.test.js

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { haversineDistance } from './Haversine'
2+
3+
describe('Testing the haversine distance calculator', () => {
4+
it('Calculate distance', () => {
5+
const distance = haversineDistance(64.1265, -21.8174, 40.7128, -74.0060)
6+
expect(distance).toBe(4208198.758424171)
7+
})
8+
it('Test validation, expect throw', () => {
9+
expect(() => haversineDistance(64.1265, -21.8174, 40.7128, '74.0060')).toThrow()
10+
})
11+
})

0 commit comments

Comments
 (0)