-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathindex.js
99 lines (85 loc) · 2.57 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
91
92
93
94
95
96
97
98
99
"use strict";
var { validateInput } = require("./input-validation");
const defaultEarthRadius = 6378137; // equatorial Earth radius
function toRadians(angleInDegrees) {
return (angleInDegrees * Math.PI) / 180;
}
function toDegrees(angleInRadians) {
return (angleInRadians * 180) / Math.PI;
}
function offset(c1, distance, earthRadius, bearing) {
var lat1 = toRadians(c1[1]);
var lon1 = toRadians(c1[0]);
var dByR = distance / earthRadius;
var lat = Math.asin(
Math.sin(lat1) * Math.cos(dByR) + Math.cos(lat1) * Math.sin(dByR) * Math.cos(bearing)
);
var lon =
lon1 +
Math.atan2(
Math.sin(bearing) * Math.sin(dByR) * Math.cos(lat1),
Math.cos(dByR) - Math.sin(lat1) * Math.sin(lat)
);
return [toDegrees(lon), toDegrees(lat)];
}
module.exports = function circleToPolygon(center, radius, options) {
var n = getNumberOfEdges(options);
var earthRadius = getEarthRadius(options);
var bearing = getBearing(options);
var direction = getDirection(options);
// validateInput() throws error on invalid input and do nothing on valid input
validateInput({ center, radius, numberOfEdges: n, earthRadius, bearing });
var start = toRadians(bearing);
var coordinates = [];
for (var i = 0; i < n; ++i) {
coordinates.push(
offset(
center, radius, earthRadius, start + (direction * 2 * Math.PI * -i) / n
)
);
}
coordinates.push(coordinates[0]);
return {
type: "Polygon",
coordinates: [coordinates]
};
};
function getNumberOfEdges(options) {
if (isUndefinedOrNull(options)) {
return 32;
} else if (isObjectNotArray(options)) {
var numberOfEdges = options.numberOfEdges;
return numberOfEdges === undefined ? 32 : numberOfEdges;
}
return options;
}
function getEarthRadius(options) {
if (isUndefinedOrNull(options)) {
return defaultEarthRadius;
} else if (isObjectNotArray(options)) {
var earthRadius = options.earthRadius;
return earthRadius === undefined ? defaultEarthRadius : earthRadius;
}
return defaultEarthRadius;
}
function getDirection(options){
if (isObjectNotArray(options) && options.rightHandRule){
return -1;
}
return 1;
}
function getBearing(options) {
if (isUndefinedOrNull(options)) {
return 0;
} else if (isObjectNotArray(options)) {
var bearing = options.bearing;
return bearing === undefined ? 0 : bearing;
}
return 0;
}
function isObjectNotArray(argument) {
return argument !== null && typeof argument === "object" && !Array.isArray(argument);
}
function isUndefinedOrNull(argument) {
return argument === null || argument === undefined;
}