-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
112 lines (88 loc) · 3.33 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
101
102
103
104
105
106
107
108
109
110
111
112
const glob = require("glob");
const fs = require("fs");
const simplify = require('simplify-geojson');
const tolerance = 0.001;
const turf = require('@turf/turf');
const path = require('path');
glob('./data/**/*', async (err, matches) => {
if (err) {
console.error('Unable to list data directories');
return;
}
for (let file of matches) {
console.log(file);
await new Promise((resolve, reject) => {
if (fs.lstatSync(file).isDirectory()) {
resolve();
return;
}
fs.readFile(file, 'utf8', (err, data) => {
if (err) {
reject();
return console.log(err);
}
const geojson = JSON.parse(data);
const name = geojson.properties.name;
console.log(name);
const properties = geojson.properties;
const geojsonAdjusted = {
'type': 'Feature',
'geometry': geojson.geometries[0]
};
const simplified = simplify(geojsonAdjusted, tolerance);
const newPath = file.replace('data', 'extracts');
const dir = path.dirname(newPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
let maxPoly = [];
for (let poly of simplified.geometry.coordinates) {
if (poly[0].length > maxPoly.length) {
maxPoly = poly[0];
}
}
let maxPolygon = turf.polygon([maxPoly]);
let resPolygon = turf.polygon([maxPoly]);;
let resPoly = null;
for (let poly of simplified.geometry.coordinates) {
if (poly[0].length < 4) {
continue;
}
const pol = turf.polygon(poly);
if (!pol || turf.booleanEqual(maxPolygon, pol)) {
continue;
}
if (turf.booleanContains(maxPolygon, pol)) {
let res = turf.difference(resPolygon, pol);
console.log('Contains');
if (res != null) {
resPolygon = res;
resPoly = res;
}
} else {
if (!resPoly) {
resPoly = pol;
} else {
resPoly = turf.union(resPoly, pol);
}
}
}
if (!resPoly) {
resPoly = maxPolygon;
} else {
resPoly = turf.union(resPolygon, resPoly);
}
resPoly.properties = properties;
fs.writeFile(newPath, JSON.stringify(resPoly), (err) => {
if (err) {
console.error(err);
reject();
return;
}
console.log(`Processing ${file} complete...`);
resolve();
});
});
});
}
});