-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathindex.js
90 lines (84 loc) · 2.25 KB
/
index.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
var invariant = require('turf-invariant');
//http://en.wikipedia.org/wiki/Haversine_formula
//http://www.movable-type.co.uk/scripts/latlong.html
/**
* Calculates the distance between two {@link Point|points} in degress, radians,
* miles, or kilometers. This uses the
* [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula)
* to account for global curvature.
*
* @module turf/distance
* @category measurement
* @param {Feature<Point>} from origin point
* @param {Feature<Point>} to destination point
* @param {String} [units=kilometers] can be degrees, radians, miles, or kilometers
* @return {Number} distance between the two points
* @example
* var point1 = {
* "type": "Feature",
* "properties": {},
* "geometry": {
* "type": "Point",
* "coordinates": [-75.343, 39.984]
* }
* };
* var point2 = {
* "type": "Feature",
* "properties": {},
* "geometry": {
* "type": "Point",
* "coordinates": [-75.534, 39.123]
* }
* };
* var units = "miles";
*
* var points = {
* "type": "FeatureCollection",
* "features": [point1, point2]
* };
*
* //=points
*
* var distance = turf.distance(point1, point2, units);
*
* //=distance
*/
module.exports = function(point1, point2, units) {
invariant.featureOf(point1, 'Point', 'distance');
invariant.featureOf(point2, 'Point', 'distance');
var coordinates1 = point1.geometry.coordinates;
var coordinates2 = point2.geometry.coordinates;
var dLat = toRad(coordinates2[1] - coordinates1[1]);
var dLon = toRad(coordinates2[0] - coordinates1[0]);
var lat1 = toRad(coordinates1[1]);
var lat2 = toRad(coordinates2[1]);
var a = Math.pow(Math.sin(dLat/2), 2) +
Math.pow(Math.sin(dLon/2), 2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var R;
switch(units) {
case 'miles':
R = 3960;
break;
case 'kilometers':
case 'kilometres':
R = 6373;
break;
case 'degrees':
R = 57.2957795;
break;
case 'radians':
R = 1;
break;
case undefined:
R = 6373;
break;
default:
throw new Error('unknown option given to "units"');
}
var distance = R * c;
return distance;
};
function toRad(degree) {
return degree * Math.PI / 180;
}