-
Notifications
You must be signed in to change notification settings - Fork 42
/
haversine.js
62 lines (51 loc) · 1.76 KB
/
haversine.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
var haversine = (function () {
var RADII = {
km: 6371,
mile: 3960,
meter: 6371000,
nmi: 3440
}
// convert to radians
var toRad = function (num) {
return num * Math.PI / 180
}
// convert coordinates to standard format based on the passed format option
var convertCoordinates = function (format, coordinates) {
switch (format) {
case '[lat,lon]':
return { latitude: coordinates[0], longitude: coordinates[1] }
case '[lon,lat]':
return { latitude: coordinates[1], longitude: coordinates[0] }
case '{lon,lat}':
return { latitude: coordinates.lat, longitude: coordinates.lon }
case '{lat,lng}':
return { latitude: coordinates.lat, longitude: coordinates.lng }
case 'geojson':
return { latitude: coordinates.geometry.coordinates[1], longitude: coordinates.geometry.coordinates[0] }
default:
return coordinates
}
}
return function haversine (startCoordinates, endCoordinates, options) {
options = options || {}
var R = options.unit in RADII
? RADII[options.unit]
: RADII.km
var start = convertCoordinates(options.format, startCoordinates)
var end = convertCoordinates(options.format, endCoordinates)
var dLat = toRad(end.latitude - start.latitude)
var dLon = toRad(end.longitude - start.longitude)
var lat1 = toRad(start.latitude)
var lat2 = toRad(end.latitude)
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2)
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
if (options.threshold) {
return options.threshold > (R * c)
}
return R * c
}
})()
if (typeof module !== 'undefined' && module.exports) {
module.exports = haversine
}