@turf/polygonize 7.0.0-alpha.2 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,293 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const tslib_1 = require("tslib");
4
- const Node_1 = tslib_1.__importDefault(require("./Node"));
5
- const Edge_1 = tslib_1.__importDefault(require("./Edge"));
6
- const EdgeRing_1 = tslib_1.__importDefault(require("./EdgeRing"));
7
- const meta_1 = require("@turf/meta");
8
- const invariant_1 = require("@turf/invariant");
9
- /**
10
- * Validates the geoJson.
11
- *
12
- * @param {GeoJSON} geoJson - input geoJson.
13
- * @throws {Error} if geoJson is invalid.
14
- */
15
- function validateGeoJson(geoJson) {
16
- if (!geoJson)
17
- throw new Error("No geojson passed");
18
- if (geoJson.type !== "FeatureCollection" &&
19
- geoJson.type !== "GeometryCollection" &&
20
- geoJson.type !== "MultiLineString" &&
21
- geoJson.type !== "LineString" &&
22
- geoJson.type !== "Feature")
23
- throw new Error(`Invalid input type '${geoJson.type}'. Geojson must be FeatureCollection, GeometryCollection, LineString, MultiLineString or Feature`);
24
- }
25
- /**
26
- * Represents a planar graph of edges and nodes that can be used to compute a polygonization.
27
- *
28
- * Although, this class is inspired by GEOS's `geos::operation::polygonize::PolygonizeGraph`,
29
- * it isn't a rewrite. As regards algorithm, this class implements the same logic, but it
30
- * isn't a javascript transcription of the C++ source.
31
- *
32
- * This graph is directed (both directions are created)
33
- */
34
- class Graph {
35
- constructor() {
36
- this.edges = []; //< {Edge[]} dirEdges
37
- // The key is the `id` of the Node (ie: coordinates.join(','))
38
- this.nodes = {};
39
- }
40
- /**
41
- * Creates a graph from a GeoJSON.
42
- *
43
- * @param {FeatureCollection<LineString>} geoJson - it must comply with the restrictions detailed in the index
44
- * @returns {Graph} - The newly created graph
45
- * @throws {Error} if geoJson is invalid.
46
- */
47
- static fromGeoJson(geoJson) {
48
- validateGeoJson(geoJson);
49
- const graph = new Graph();
50
- meta_1.flattenEach(geoJson, (feature) => {
51
- invariant_1.featureOf(feature, "LineString", "Graph::fromGeoJson");
52
- // When a LineString if formed by many segments, split them
53
- meta_1.coordReduce(feature, (prev, cur) => {
54
- if (prev) {
55
- const start = graph.getNode(prev), end = graph.getNode(cur);
56
- graph.addEdge(start, end);
57
- }
58
- return cur;
59
- });
60
- });
61
- return graph;
62
- }
63
- /**
64
- * Creates or get a Node.
65
- *
66
- * @param {number[]} coordinates - Coordinates of the node
67
- * @returns {Node} - The created or stored node
68
- */
69
- getNode(coordinates) {
70
- const id = Node_1.default.buildId(coordinates);
71
- let node = this.nodes[id];
72
- if (!node)
73
- node = this.nodes[id] = new Node_1.default(coordinates);
74
- return node;
75
- }
76
- /**
77
- * Adds an Edge and its symetricall.
78
- *
79
- * Edges are added symetrically, i.e.: we also add its symetric
80
- *
81
- * @param {Node} from - Node which starts the Edge
82
- * @param {Node} to - Node which ends the Edge
83
- */
84
- addEdge(from, to) {
85
- const edge = new Edge_1.default(from, to), symetricEdge = edge.getSymetric();
86
- this.edges.push(edge);
87
- this.edges.push(symetricEdge);
88
- }
89
- /**
90
- * Removes Dangle Nodes (nodes with grade 1).
91
- */
92
- deleteDangles() {
93
- Object.keys(this.nodes)
94
- .map((id) => this.nodes[id])
95
- .forEach((node) => this._removeIfDangle(node));
96
- }
97
- /**
98
- * Check if node is dangle, if so, remove it.
99
- *
100
- * It calls itself recursively, removing a dangling node might cause another dangling node
101
- *
102
- * @param {Node} node - Node to check if it's a dangle
103
- */
104
- _removeIfDangle(node) {
105
- // As edges are directed and symetrical, we count only innerEdges
106
- if (node.innerEdges.length <= 1) {
107
- const outerNodes = node.getOuterEdges().map((e) => e.to);
108
- this.removeNode(node);
109
- outerNodes.forEach((n) => this._removeIfDangle(n));
110
- }
111
- }
112
- /**
113
- * Delete cut-edges (bridge edges).
114
- *
115
- * The graph will be traversed, all the edges will be labeled according the ring
116
- * in which they are. (The label is a number incremented by 1). Edges with the same
117
- * label are cut-edges.
118
- */
119
- deleteCutEdges() {
120
- this._computeNextCWEdges();
121
- this._findLabeledEdgeRings();
122
- // Cut-edges (bridges) are edges where both edges have the same label
123
- this.edges.forEach((edge) => {
124
- if (edge.label === edge.symetric.label) {
125
- this.removeEdge(edge.symetric);
126
- this.removeEdge(edge);
127
- }
128
- });
129
- }
130
- /**
131
- * Set the `next` property of each Edge.
132
- *
133
- * The graph will be transversed in a CW form, so, we set the next of the symetrical edge as the previous one.
134
- * OuterEdges are sorted CCW.
135
- *
136
- * @param {Node} [node] - If no node is passed, the function calls itself for every node in the Graph
137
- */
138
- _computeNextCWEdges(node) {
139
- if (typeof node === "undefined") {
140
- Object.keys(this.nodes).forEach((id) => this._computeNextCWEdges(this.nodes[id]));
141
- }
142
- else {
143
- node.getOuterEdges().forEach((edge, i) => {
144
- node.getOuterEdge((i === 0 ? node.getOuterEdges().length : i) - 1).symetric.next = edge;
145
- });
146
- }
147
- }
148
- /**
149
- * Computes the next edge pointers going CCW around the given node, for the given edgering label.
150
- *
151
- * This algorithm has the effect of converting maximal edgerings into minimal edgerings
152
- *
153
- * XXX: method literally transcribed from `geos::operation::polygonize::PolygonizeGraph::computeNextCCWEdges`,
154
- * could be written in a more javascript way.
155
- *
156
- * @param {Node} node - Node
157
- * @param {number} label - Ring's label
158
- */
159
- _computeNextCCWEdges(node, label) {
160
- const edges = node.getOuterEdges();
161
- let firstOutDE, prevInDE;
162
- for (let i = edges.length - 1; i >= 0; --i) {
163
- let de = edges[i], sym = de.symetric, outDE, inDE;
164
- if (de.label === label)
165
- outDE = de;
166
- if (sym.label === label)
167
- inDE = sym;
168
- if (!outDE || !inDE)
169
- // This edge is not in edgering
170
- continue;
171
- if (inDE)
172
- prevInDE = inDE;
173
- if (outDE) {
174
- if (prevInDE) {
175
- prevInDE.next = outDE;
176
- prevInDE = undefined;
177
- }
178
- if (!firstOutDE)
179
- firstOutDE = outDE;
180
- }
181
- }
182
- if (prevInDE)
183
- prevInDE.next = firstOutDE;
184
- }
185
- /**
186
- * Finds rings and labels edges according to which rings are.
187
- *
188
- * The label is a number which is increased for each ring.
189
- *
190
- * @returns {Edge[]} edges that start rings
191
- */
192
- _findLabeledEdgeRings() {
193
- const edgeRingStarts = [];
194
- let label = 0;
195
- this.edges.forEach((edge) => {
196
- if (edge.label >= 0)
197
- return;
198
- edgeRingStarts.push(edge);
199
- let e = edge;
200
- do {
201
- e.label = label;
202
- e = e.next;
203
- } while (!edge.isEqual(e));
204
- label++;
205
- });
206
- return edgeRingStarts;
207
- }
208
- /**
209
- * Computes the EdgeRings formed by the edges in this graph.
210
- *
211
- * @returns {EdgeRing[]} - A list of all the EdgeRings in the graph.
212
- */
213
- getEdgeRings() {
214
- this._computeNextCWEdges();
215
- // Clear labels
216
- this.edges.forEach((edge) => {
217
- edge.label = undefined;
218
- });
219
- this._findLabeledEdgeRings().forEach((edge) => {
220
- // convertMaximalToMinimalEdgeRings
221
- this._findIntersectionNodes(edge).forEach((node) => {
222
- this._computeNextCCWEdges(node, edge.label);
223
- });
224
- });
225
- const edgeRingList = [];
226
- // find all edgerings
227
- this.edges.forEach((edge) => {
228
- if (edge.ring)
229
- return;
230
- edgeRingList.push(this._findEdgeRing(edge));
231
- });
232
- return edgeRingList;
233
- }
234
- /**
235
- * Find all nodes in a Maxima EdgeRing which are self-intersection nodes.
236
- *
237
- * @param {Node} startEdge - Start Edge of the Ring
238
- * @returns {Node[]} - intersection nodes
239
- */
240
- _findIntersectionNodes(startEdge) {
241
- const intersectionNodes = [];
242
- let edge = startEdge;
243
- do {
244
- // getDegree
245
- let degree = 0;
246
- edge.from.getOuterEdges().forEach((e) => {
247
- if (e.label === startEdge.label)
248
- ++degree;
249
- });
250
- if (degree > 1)
251
- intersectionNodes.push(edge.from);
252
- edge = edge.next;
253
- } while (!startEdge.isEqual(edge));
254
- return intersectionNodes;
255
- }
256
- /**
257
- * Get the edge-ring which starts from the provided Edge.
258
- *
259
- * @param {Edge} startEdge - starting edge of the edge ring
260
- * @returns {EdgeRing} - EdgeRing which start Edge is the provided one.
261
- */
262
- _findEdgeRing(startEdge) {
263
- let edge = startEdge;
264
- const edgeRing = new EdgeRing_1.default();
265
- do {
266
- edgeRing.push(edge);
267
- edge.ring = edgeRing;
268
- edge = edge.next;
269
- } while (!startEdge.isEqual(edge));
270
- return edgeRing;
271
- }
272
- /**
273
- * Removes a node from the Graph.
274
- *
275
- * It also removes edges asociated to that node
276
- * @param {Node} node - Node to be removed
277
- */
278
- removeNode(node) {
279
- node.getOuterEdges().forEach((edge) => this.removeEdge(edge));
280
- node.innerEdges.forEach((edge) => this.removeEdge(edge));
281
- delete this.nodes[node.id];
282
- }
283
- /**
284
- * Remove edge from the graph and deletes the edge.
285
- *
286
- * @param {Edge} edge - Edge to be removed
287
- */
288
- removeEdge(edge) {
289
- this.edges = this.edges.filter((e) => !e.isEqual(edge));
290
- edge.deleteEdge();
291
- }
292
- }
293
- exports.default = Graph;
@@ -1,40 +0,0 @@
1
- import Edge from "./Edge";
2
- /**
3
- * Node
4
- */
5
- export default class Node {
6
- static buildId(coordinates: number[]): string;
7
- id: string;
8
- coordinates: number[];
9
- innerEdges: Edge[];
10
- private outerEdges;
11
- private outerEdgesSorted;
12
- constructor(coordinates: number[]);
13
- removeInnerEdge(edge: Edge): void;
14
- removeOuterEdge(edge: Edge): void;
15
- /**
16
- * Outer edges are stored CCW order.
17
- *
18
- * @memberof Node
19
- * @param {Edge} edge - Edge to add as an outerEdge.
20
- */
21
- addOuterEdge(edge: Edge): void;
22
- /**
23
- * Sorts outer edges in CCW way.
24
- *
25
- * @memberof Node
26
- * @private
27
- */
28
- sortOuterEdges(): void;
29
- /**
30
- * Retrieves outer edges.
31
- *
32
- * They are sorted if they aren't in the CCW order.
33
- *
34
- * @memberof Node
35
- * @returns {Edge[]} - List of outer edges sorted in a CCW order.
36
- */
37
- getOuterEdges(): Edge[];
38
- getOuterEdge(i: number): Edge;
39
- addInnerEdge(edge: Edge): void;
40
- }
@@ -1,93 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const util_1 = require("./util");
4
- /**
5
- * Node
6
- */
7
- class Node {
8
- constructor(coordinates) {
9
- this.id = Node.buildId(coordinates);
10
- this.coordinates = coordinates; //< {Number[]}
11
- this.innerEdges = []; //< {Edge[]}
12
- // We wil store to (out) edges in an CCW order as geos::planargraph::DirectedEdgeStar does
13
- this.outerEdges = []; //< {Edge[]}
14
- this.outerEdgesSorted = false; //< {Boolean} flag that stores if the outer Edges had been sorted
15
- }
16
- static buildId(coordinates) {
17
- return coordinates.join(",");
18
- }
19
- removeInnerEdge(edge) {
20
- this.innerEdges = this.innerEdges.filter((e) => e.from.id !== edge.from.id);
21
- }
22
- removeOuterEdge(edge) {
23
- this.outerEdges = this.outerEdges.filter((e) => e.to.id !== edge.to.id);
24
- }
25
- /**
26
- * Outer edges are stored CCW order.
27
- *
28
- * @memberof Node
29
- * @param {Edge} edge - Edge to add as an outerEdge.
30
- */
31
- addOuterEdge(edge) {
32
- this.outerEdges.push(edge);
33
- this.outerEdgesSorted = false;
34
- }
35
- /**
36
- * Sorts outer edges in CCW way.
37
- *
38
- * @memberof Node
39
- * @private
40
- */
41
- sortOuterEdges() {
42
- if (!this.outerEdgesSorted) {
43
- //this.outerEdges.sort((a, b) => a.compareTo(b));
44
- // Using this comparator in order to be deterministic
45
- this.outerEdges.sort((a, b) => {
46
- const aNode = a.to, bNode = b.to;
47
- if (aNode.coordinates[0] - this.coordinates[0] >= 0 &&
48
- bNode.coordinates[0] - this.coordinates[0] < 0)
49
- return 1;
50
- if (aNode.coordinates[0] - this.coordinates[0] < 0 &&
51
- bNode.coordinates[0] - this.coordinates[0] >= 0)
52
- return -1;
53
- if (aNode.coordinates[0] - this.coordinates[0] === 0 &&
54
- bNode.coordinates[0] - this.coordinates[0] === 0) {
55
- if (aNode.coordinates[1] - this.coordinates[1] >= 0 ||
56
- bNode.coordinates[1] - this.coordinates[1] >= 0)
57
- return aNode.coordinates[1] - bNode.coordinates[1];
58
- return bNode.coordinates[1] - aNode.coordinates[1];
59
- }
60
- const det = util_1.orientationIndex(this.coordinates, aNode.coordinates, bNode.coordinates);
61
- if (det < 0)
62
- return 1;
63
- if (det > 0)
64
- return -1;
65
- const d1 = Math.pow(aNode.coordinates[0] - this.coordinates[0], 2) +
66
- Math.pow(aNode.coordinates[1] - this.coordinates[1], 2), d2 = Math.pow(bNode.coordinates[0] - this.coordinates[0], 2) +
67
- Math.pow(bNode.coordinates[1] - this.coordinates[1], 2);
68
- return d1 - d2;
69
- });
70
- this.outerEdgesSorted = true;
71
- }
72
- }
73
- /**
74
- * Retrieves outer edges.
75
- *
76
- * They are sorted if they aren't in the CCW order.
77
- *
78
- * @memberof Node
79
- * @returns {Edge[]} - List of outer edges sorted in a CCW order.
80
- */
81
- getOuterEdges() {
82
- this.sortOuterEdges();
83
- return this.outerEdges;
84
- }
85
- getOuterEdge(i) {
86
- this.sortOuterEdges();
87
- return this.outerEdges[i];
88
- }
89
- addInnerEdge(edge) {
90
- this.innerEdges.push(edge);
91
- }
92
- }
93
- exports.default = Node;
@@ -1,46 +0,0 @@
1
- import { Feature, Polygon } from "geojson";
2
- /**
3
- * Returns the direction of the point q relative to the vector p1 -> p2.
4
- *
5
- * Implementation of geos::algorithm::CGAlgorithm::orientationIndex()
6
- * (same as geos::algorithm::CGAlgorithm::computeOrientation())
7
- *
8
- * @param {number[]} p1 - the origin point of the vector
9
- * @param {number[]} p2 - the final point of the vector
10
- * @param {number[]} q - the point to compute the direction to
11
- *
12
- * @returns {number} - 1 if q is ccw (left) from p1->p2,
13
- * -1 if q is cw (right) from p1->p2,
14
- * 0 if q is colinear with p1->p2
15
- */
16
- export declare function orientationIndex(p1: number[], p2: number[], q: number[]): number;
17
- /**
18
- * Checks if two envelopes are equal.
19
- *
20
- * The function assumes that the arguments are envelopes, i.e.: Rectangular polygon
21
- *
22
- * @param {Feature<Polygon>} env1 - Envelope
23
- * @param {Feature<Polygon>} env2 - Envelope
24
- * @returns {boolean} - True if the envelopes are equal
25
- */
26
- export declare function envelopeIsEqual(env1: Feature<Polygon>, env2: Feature<Polygon>): boolean;
27
- /**
28
- * Check if a envelope is contained in other one.
29
- *
30
- * The function assumes that the arguments are envelopes, i.e.: Convex polygon
31
- * XXX: Envelopes are rectangular, checking if a point is inside a rectangule is something easy,
32
- * this could be further improved.
33
- *
34
- * @param {Feature<Polygon>} self - Envelope
35
- * @param {Feature<Polygon>} env - Envelope
36
- * @returns {boolean} - True if env is contained in self
37
- */
38
- export declare function envelopeContains(self: Feature<Polygon>, env: Feature<Polygon>): boolean;
39
- /**
40
- * Checks if two coordinates are equal.
41
- *
42
- * @param {number[]} coord1 - First coordinate
43
- * @param {number[]} coord2 - Second coordinate
44
- * @returns {boolean} - True if coordinates are equal
45
- */
46
- export declare function coordinatesEqual(coord1: number[], coord2: number[]): boolean;
@@ -1,71 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const tslib_1 = require("tslib");
4
- const boolean_point_in_polygon_1 = tslib_1.__importDefault(require("@turf/boolean-point-in-polygon"));
5
- const helpers_1 = require("@turf/helpers");
6
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign#Polyfill
7
- function mathSign(x) {
8
- return ((x > 0) - (x < 0) || +x);
9
- }
10
- /**
11
- * Returns the direction of the point q relative to the vector p1 -> p2.
12
- *
13
- * Implementation of geos::algorithm::CGAlgorithm::orientationIndex()
14
- * (same as geos::algorithm::CGAlgorithm::computeOrientation())
15
- *
16
- * @param {number[]} p1 - the origin point of the vector
17
- * @param {number[]} p2 - the final point of the vector
18
- * @param {number[]} q - the point to compute the direction to
19
- *
20
- * @returns {number} - 1 if q is ccw (left) from p1->p2,
21
- * -1 if q is cw (right) from p1->p2,
22
- * 0 if q is colinear with p1->p2
23
- */
24
- function orientationIndex(p1, p2, q) {
25
- const dx1 = p2[0] - p1[0], dy1 = p2[1] - p1[1], dx2 = q[0] - p2[0], dy2 = q[1] - p2[1];
26
- return mathSign(dx1 * dy2 - dx2 * dy1);
27
- }
28
- exports.orientationIndex = orientationIndex;
29
- /**
30
- * Checks if two envelopes are equal.
31
- *
32
- * The function assumes that the arguments are envelopes, i.e.: Rectangular polygon
33
- *
34
- * @param {Feature<Polygon>} env1 - Envelope
35
- * @param {Feature<Polygon>} env2 - Envelope
36
- * @returns {boolean} - True if the envelopes are equal
37
- */
38
- function envelopeIsEqual(env1, env2) {
39
- const envX1 = env1.geometry.coordinates[0].map((c) => c[0]), envY1 = env1.geometry.coordinates[0].map((c) => c[1]), envX2 = env2.geometry.coordinates[0].map((c) => c[0]), envY2 = env2.geometry.coordinates[0].map((c) => c[1]);
40
- return (Math.max.apply(null, envX1) === Math.max.apply(null, envX2) &&
41
- Math.max.apply(null, envY1) === Math.max.apply(null, envY2) &&
42
- Math.min.apply(null, envX1) === Math.min.apply(null, envX2) &&
43
- Math.min.apply(null, envY1) === Math.min.apply(null, envY2));
44
- }
45
- exports.envelopeIsEqual = envelopeIsEqual;
46
- /**
47
- * Check if a envelope is contained in other one.
48
- *
49
- * The function assumes that the arguments are envelopes, i.e.: Convex polygon
50
- * XXX: Envelopes are rectangular, checking if a point is inside a rectangule is something easy,
51
- * this could be further improved.
52
- *
53
- * @param {Feature<Polygon>} self - Envelope
54
- * @param {Feature<Polygon>} env - Envelope
55
- * @returns {boolean} - True if env is contained in self
56
- */
57
- function envelopeContains(self, env) {
58
- return env.geometry.coordinates[0].every((c) => boolean_point_in_polygon_1.default(helpers_1.point(c), self));
59
- }
60
- exports.envelopeContains = envelopeContains;
61
- /**
62
- * Checks if two coordinates are equal.
63
- *
64
- * @param {number[]} coord1 - First coordinate
65
- * @param {number[]} coord2 - Second coordinate
66
- * @returns {boolean} - True if coordinates are equal
67
- */
68
- function coordinatesEqual(coord1, coord2) {
69
- return coord1[0] === coord2[0] && coord1[1] === coord2[1];
70
- }
71
- exports.coordinatesEqual = coordinatesEqual;