-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
100 lines (94 loc) · 2.54 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
100
// Inspired by https://www.johndcook.com/blog/2009/04/27/converting-miles-to-degrees-longitude-or-latitude/\
const earthRadiusMeters = 6378137;
const radiansToDegrees = 180.0 / Math.PI;
const degreesToRadians = Math.PI / 180.0;
function changeInLatitude(meters) {
return (meters / earthRadiusMeters) * radiansToDegrees;
}
function changeInLongitude(latitude, meters) {
const r = earthRadiusMeters * Math.cos(latitude * degreesToRadians);
return (meters / r) * radiansToDegrees;
}
function flatten(array, accumulator = []) {
return array.reduce((acc, item) => {
if (item instanceof Array) {
return flatten(item, acc);
}
acc.push(item);
return acc;
}, accumulator);
}
module.exports = function boxAround(__feature, options = { paddingMeters: 10000 }) {
let coordinates = [];
if (__feature.type === 'Feature') {
coordinates = flatten(__feature.geometry.coordinates);
}
if (__feature.type === 'FeatureCollection') {
coordinates = flatten(
__feature.features.map(
feature => feature.geometry.coordinates,
),
);
}
let maxLat;
let maxLng;
let minLat;
let minLng;
while (coordinates.length) {
const lat = coordinates.pop();
const lng = coordinates.pop();
if (typeof maxLat === 'undefined') {
maxLat = lat;
}
if (typeof maxLng === 'undefined') {
maxLng = lng;
}
if (typeof minLat === 'undefined') {
minLat = lat;
}
if (typeof minLng === 'undefined') {
minLng = lng;
}
if (lng < minLng) {
minLng = lng;
}
if (lat < minLat) {
minLat = lat;
}
if (lng > maxLng) {
maxLng = lng;
}
if (lat > maxLat) {
maxLat = lat;
}
}
return {
type: 'Feature',
properties: {},
geometry: {
type: 'Polygon',
coordinates: [[
[
maxLng + changeInLongitude(maxLat, options.paddingMeters),
maxLat + changeInLatitude(options.paddingMeters),
],
[
maxLng + changeInLongitude(minLat, options.paddingMeters),
minLat - changeInLatitude(options.paddingMeters),
],
[
minLng - changeInLongitude(minLat, options.paddingMeters),
minLat - changeInLatitude(options.paddingMeters),
],
[
minLng - changeInLongitude(maxLat, options.paddingMeters),
maxLat + changeInLatitude(options.paddingMeters),
],
[
maxLng + changeInLongitude(maxLat, options.paddingMeters),
maxLat + changeInLatitude(options.paddingMeters)
],
]]
},
}
}