@maplibre/geojson-vt 6.1.0 → 6.1.1

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,2296 +1,1995 @@
1
- (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.geojsonvt = {}));
5
- })(this, (function (exports) { 'use strict';
1
+ (function(global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.geojsonvt = {})));
5
+ })(this, function(exports) {
6
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
6
7
 
8
+ //#region src/simplify.ts
7
9
  /**
8
- * calculate simplification data using optimized Douglas-Peucker algorithm
9
- * @param coords - flat array of coordinates
10
- * @param first - index of the first coordinate in the segment
11
- * @param last - index of the last coordinate in the segment
12
- * @param sqTolerance - square tolerance value
13
- */
14
- function simplify(coords, first, last, sqTolerance) {
15
- let maxSqDist = sqTolerance;
16
- const mid = first + ((last - first) >> 1);
17
- let minPosToMid = last - first;
18
- let index;
19
- const ax = coords[first];
20
- const ay = coords[first + 1];
21
- const bx = coords[last];
22
- const by = coords[last + 1];
23
- for (let i = first + 3; i < last; i += 3) {
24
- const d = getSqSegDist(coords[i], coords[i + 1], ax, ay, bx, by);
25
- if (d > maxSqDist) {
26
- index = i;
27
- maxSqDist = d;
28
- continue;
29
- }
30
- if (d === maxSqDist) {
31
- // a workaround to ensure we choose a pivot close to the middle of the list,
32
- // reducing recursion depth, for certain degenerate inputs
33
- // https://github.com/mapbox/geojson-vt/issues/104
34
- const posToMid = Math.abs(i - mid);
35
- if (posToMid < minPosToMid) {
36
- index = i;
37
- minPosToMid = posToMid;
38
- }
39
- }
40
- }
41
- if (maxSqDist > sqTolerance) {
42
- if (index - first > 3)
43
- simplify(coords, first, index, sqTolerance);
44
- coords[index + 2] = maxSqDist;
45
- if (last - index > 3)
46
- simplify(coords, index, last, sqTolerance);
47
- }
48
- }
49
- /**
50
- * Claculates the square distance from a point to a segment
51
- * @param px - x coordinate of the point
52
- * @param py - y coordinate of the point
53
- * @param x - x coordinate of the first segment endpoint
54
- * @param y - y coordinate of the first segment endpoint
55
- * @param bx - x coordinate of the second segment endpoint
56
- * @param by - y coordinate of the second segment endpoint
57
- * @returns square distance from a point to a segment
58
- */
59
- function getSqSegDist(px, py, x, y, bx, by) {
60
- let dx = bx - x;
61
- let dy = by - y;
62
- if (dx !== 0 || dy !== 0) {
63
- const t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy);
64
- if (t > 1) {
65
- x = bx;
66
- y = by;
67
- }
68
- else if (t > 0) {
69
- x += dx * t;
70
- y += dy * t;
71
- }
72
- }
73
- dx = px - x;
74
- dy = py - y;
75
- return dx * dx + dy * dy;
76
- }
10
+ * calculate simplification data using optimized Douglas-Peucker algorithm
11
+ * @param coords - flat array of coordinates
12
+ * @param first - index of the first coordinate in the segment
13
+ * @param last - index of the last coordinate in the segment
14
+ * @param sqTolerance - square tolerance value
15
+ */
16
+ function simplify(coords, first, last, sqTolerance) {
17
+ let maxSqDist = sqTolerance;
18
+ const mid = first + (last - first >> 1);
19
+ let minPosToMid = last - first;
20
+ let index;
21
+ const ax = coords[first];
22
+ const ay = coords[first + 1];
23
+ const bx = coords[last];
24
+ const by = coords[last + 1];
25
+ for (let i = first + 3; i < last; i += 3) {
26
+ const d = getSqSegDist(coords[i], coords[i + 1], ax, ay, bx, by);
27
+ if (d > maxSqDist) {
28
+ index = i;
29
+ maxSqDist = d;
30
+ continue;
31
+ }
32
+ if (d === maxSqDist) {
33
+ const posToMid = Math.abs(i - mid);
34
+ if (posToMid < minPosToMid) {
35
+ index = i;
36
+ minPosToMid = posToMid;
37
+ }
38
+ }
39
+ }
40
+ if (maxSqDist > sqTolerance) {
41
+ if (index - first > 3) simplify(coords, first, index, sqTolerance);
42
+ coords[index + 2] = maxSqDist;
43
+ if (last - index > 3) simplify(coords, index, last, sqTolerance);
44
+ }
45
+ }
46
+ /**
47
+ * Claculates the square distance from a point to a segment
48
+ * @param px - x coordinate of the point
49
+ * @param py - y coordinate of the point
50
+ * @param x - x coordinate of the first segment endpoint
51
+ * @param y - y coordinate of the first segment endpoint
52
+ * @param bx - x coordinate of the second segment endpoint
53
+ * @param by - y coordinate of the second segment endpoint
54
+ * @returns square distance from a point to a segment
55
+ */
56
+ function getSqSegDist(px, py, x, y, bx, by) {
57
+ let dx = bx - x;
58
+ let dy = by - y;
59
+ if (dx !== 0 || dy !== 0) {
60
+ const t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy);
61
+ if (t > 1) {
62
+ x = bx;
63
+ y = by;
64
+ } else if (t > 0) {
65
+ x += dx * t;
66
+ y += dy * t;
67
+ }
68
+ }
69
+ dx = px - x;
70
+ dy = py - y;
71
+ return dx * dx + dy * dy;
72
+ }
77
73
 
74
+ //#endregion
75
+ //#region src/feature.ts
78
76
  /**
79
- *
80
- * @param id - the feature's ID
81
- * @param type - the feature's type
82
- * @param geom - the feature's geometry
83
- * @param tags - the feature's properties
84
- * @returns the created feature
85
- */
86
- function createFeature(id, type, geom, tags) {
87
- // This is mostly for TypeScript type narrowing
88
- const data = { type, geom };
89
- const feature = {
90
- id: id == null ? null : id,
91
- type: data.type,
92
- geometry: data.geom,
93
- tags,
94
- minX: Infinity,
95
- minY: Infinity,
96
- maxX: -Infinity,
97
- maxY: -Infinity
98
- };
99
- switch (data.type) {
100
- case 'Point':
101
- case 'MultiPoint':
102
- calcLineBBox(feature, data.geom);
103
- break;
104
- case 'LineString':
105
- calcLineBBox(feature, data.geom.points);
106
- break;
107
- case 'Polygon':
108
- // the outer ring (ie [0]) contains all inner rings
109
- calcLineBBox(feature, data.geom[0].points);
110
- break;
111
- case 'MultiLineString':
112
- for (const line of data.geom) {
113
- calcLineBBox(feature, line.points);
114
- }
115
- break;
116
- case 'MultiPolygon':
117
- for (const polygon of data.geom) {
118
- // the outer ring (ie [0]) contains all inner rings
119
- calcLineBBox(feature, polygon[0].points);
120
- }
121
- break;
122
- }
123
- return feature;
124
- }
125
- function optimizeLineMemory(line) {
126
- const lineImmutable = line;
127
- if (line.points.length > 64) {
128
- lineImmutable.points = new Float64Array(line.points);
129
- }
130
- }
131
- function calcLineBBox(feature, geom) {
132
- for (let i = 0; i < geom.length; i += 3) {
133
- feature.minX = Math.min(feature.minX, geom[i]);
134
- feature.minY = Math.min(feature.minY, geom[i + 1]);
135
- feature.maxX = Math.max(feature.maxX, geom[i]);
136
- feature.maxY = Math.max(feature.maxY, geom[i + 1]);
137
- }
138
- }
77
+ *
78
+ * @param id - the feature's ID
79
+ * @param type - the feature's type
80
+ * @param geom - the feature's geometry
81
+ * @param tags - the feature's properties
82
+ * @returns the created feature
83
+ */
84
+ function createFeature(id, type, geom, tags) {
85
+ const data = {
86
+ type,
87
+ geom
88
+ };
89
+ const feature = {
90
+ id: id == null ? null : id,
91
+ type: data.type,
92
+ geometry: data.geom,
93
+ tags,
94
+ minX: Infinity,
95
+ minY: Infinity,
96
+ maxX: -Infinity,
97
+ maxY: -Infinity
98
+ };
99
+ switch (data.type) {
100
+ case "Point":
101
+ case "MultiPoint":
102
+ calcLineBBox(feature, data.geom);
103
+ break;
104
+ case "LineString":
105
+ calcLineBBox(feature, data.geom.points);
106
+ break;
107
+ case "Polygon":
108
+ calcLineBBox(feature, data.geom[0].points);
109
+ break;
110
+ case "MultiLineString":
111
+ for (const line of data.geom) calcLineBBox(feature, line.points);
112
+ break;
113
+ case "MultiPolygon":
114
+ for (const polygon of data.geom) calcLineBBox(feature, polygon[0].points);
115
+ break;
116
+ }
117
+ return feature;
118
+ }
119
+ function optimizeLineMemory(line) {
120
+ const lineImmutable = line;
121
+ if (line.points.length > 64) lineImmutable.points = new Float64Array(line.points);
122
+ }
123
+ function calcLineBBox(feature, geom) {
124
+ for (let i = 0; i < geom.length; i += 3) {
125
+ feature.minX = Math.min(feature.minX, geom[i]);
126
+ feature.minY = Math.min(feature.minY, geom[i + 1]);
127
+ feature.maxX = Math.max(feature.maxX, geom[i]);
128
+ feature.maxY = Math.max(feature.maxY, geom[i + 1]);
129
+ }
130
+ }
139
131
 
140
- /**
141
- * converts GeoJSON to internal source features (an intermediate projected JSON vector format with simplification data)
142
- * @param data
143
- * @param options
144
- * @returns
145
- */
146
- function convertToInternal(data, options) {
147
- const features = [];
148
- switch (data.type) {
149
- case 'FeatureCollection':
150
- for (let i = 0; i < data.features.length; i++) {
151
- featureToInternal(features, data.features[i], options, i);
152
- }
153
- break;
154
- case 'Feature':
155
- featureToInternal(features, data, options);
156
- break;
157
- default:
158
- featureToInternal(features, { geometry: data, properties: undefined }, options);
159
- }
160
- return features;
161
- }
162
- function featureToInternal(features, geojson, options, index) {
163
- if (!geojson.geometry)
164
- return;
165
- if (geojson.geometry.type === 'GeometryCollection') {
166
- convertGeometryCollection(features, geojson, geojson.geometry, options, index);
167
- return;
168
- }
169
- const coords = geojson.geometry.coordinates;
170
- if (!coords?.length)
171
- return;
172
- const id = getFeatureId(geojson, options, index);
173
- const tolerance = Math.pow(options.tolerance / ((1 << options.maxZoom) * options.extent), 2);
174
- switch (geojson.geometry.type) {
175
- case 'Point':
176
- convertPointFeature(features, id, geojson.geometry, geojson.properties);
177
- return;
178
- case 'MultiPoint':
179
- convertMultiPointFeature(features, id, geojson.geometry, geojson.properties);
180
- return;
181
- case 'LineString':
182
- convertLineStringFeature(features, id, geojson.geometry, tolerance, geojson.properties);
183
- return;
184
- case 'MultiLineString':
185
- convertMultiLineStringFeature(features, id, geojson.geometry, tolerance, options, geojson.properties);
186
- return;
187
- case 'Polygon':
188
- convertPolygonFeature(features, id, geojson.geometry, tolerance, geojson.properties);
189
- return;
190
- case 'MultiPolygon':
191
- convertMultiPolygonFeature(features, id, geojson.geometry, tolerance, geojson.properties);
192
- return;
193
- default:
194
- throw new Error('Input data is not a valid GeoJSON object.');
195
- }
196
- }
197
- function getFeatureId(geojson, options, index) {
198
- if (options.promoteId) {
199
- return geojson.properties?.[options.promoteId];
200
- }
201
- if (options.generateId) {
202
- return index || 0;
203
- }
204
- return geojson.id;
205
- }
206
- function convertGeometryCollection(features, geojson, geometry, options, index) {
207
- for (const geom of geometry.geometries) {
208
- featureToInternal(features, {
209
- id: geojson.id,
210
- geometry: geom,
211
- properties: geojson.properties
212
- }, options, index);
213
- }
214
- }
215
- function convertPointFeature(features, id, geom, properties) {
216
- const out = [];
217
- out.push(projectX(geom.coordinates[0]), projectY(geom.coordinates[1]), 0);
218
- features.push(createFeature(id, 'Point', out, properties));
219
- }
220
- function convertMultiPointFeature(features, id, geom, properties) {
221
- const out = [];
222
- for (const coords of geom.coordinates) {
223
- out.push(projectX(coords[0]), projectY(coords[1]), 0);
224
- }
225
- features.push(createFeature(id, 'MultiPoint', out, properties));
226
- }
227
- function convertLineStringFeature(features, id, geom, tolerance, properties) {
228
- const out = { points: [] };
229
- convertLine(geom.coordinates, out, tolerance, false);
230
- features.push(createFeature(id, 'LineString', out, properties));
231
- }
232
- function convertMultiLineStringFeature(features, id, geom, tolerance, options, properties) {
233
- if (options.lineMetrics) {
234
- // explode into linestrings to be able to track metrics
235
- for (const line of geom.coordinates) {
236
- const out = { points: [] };
237
- convertLine(line, out, tolerance, false);
238
- features.push(createFeature(id, 'LineString', out, properties));
239
- }
240
- }
241
- else {
242
- const out = [];
243
- convertLines(geom.coordinates, out, tolerance, false);
244
- features.push(createFeature(id, 'MultiLineString', out, properties));
245
- }
246
- }
247
- function convertPolygonFeature(features, id, geom, tolerance, properties) {
248
- const out = [];
249
- convertLines(geom.coordinates, out, tolerance, true);
250
- features.push(createFeature(id, 'Polygon', out, properties));
251
- }
252
- function convertMultiPolygonFeature(features, id, geom, tolerance, properties) {
253
- const out = [];
254
- for (const polygon of geom.coordinates) {
255
- const polygonOut = [];
256
- convertLines(polygon, polygonOut, tolerance, true);
257
- out.push(polygonOut);
258
- }
259
- features.push(createFeature(id, 'MultiPolygon', out, properties));
260
- }
261
- function convertLine(ring, out, tolerance, isPolygon) {
262
- let x0, y0;
263
- let size = 0;
264
- for (let j = 0; j < ring.length; j++) {
265
- const x = projectX(ring[j][0]);
266
- const y = projectY(ring[j][1]);
267
- out.points.push(x, y, 0);
268
- if (j > 0) {
269
- if (isPolygon) {
270
- size += (x0 * y - x * y0) / 2; // area
271
- }
272
- else {
273
- size += Math.sqrt(Math.pow(x - x0, 2) + Math.pow(y - y0, 2)); // length
274
- }
275
- }
276
- x0 = x;
277
- y0 = y;
278
- }
279
- const last = out.points.length - 3;
280
- out.points[2] = 1;
281
- if (tolerance > 0)
282
- simplify(out.points, 0, last, tolerance);
283
- out.points[last + 2] = 1;
284
- optimizeLineMemory(out);
285
- out.size = Math.abs(size);
286
- out.start = 0;
287
- out.end = out.size;
288
- }
289
- function convertLines(rings, out, tolerance, isPolygon) {
290
- for (let i = 0; i < rings.length; i++) {
291
- const geom = { points: [] };
292
- convertLine(rings[i], geom, tolerance, isPolygon);
293
- out.push(geom);
294
- }
295
- }
296
- /**
297
- * Convert longitude to spherical mercator in [0..1] range
298
- */
299
- function projectX(x) {
300
- return x / 360 + 0.5;
301
- }
302
- /**
303
- * Convert latitude to spherical mercator in [0..1] range
304
- */
305
- function projectY(y) {
306
- const sin = Math.sin(y * Math.PI / 180);
307
- const y2 = 0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI;
308
- return y2 < 0 ? 0 : y2 > 1 ? 1 : y2;
309
- }
132
+ //#endregion
133
+ //#region src/convert.ts
134
+ const MAX_GEOMETRY_COLLECTION_DEPTH = 1024;
135
+ /**
136
+ * converts GeoJSON to internal source features (an intermediate projected JSON vector format with simplification data)
137
+ * @param data
138
+ * @param options
139
+ * @returns
140
+ */
141
+ function convertToInternal(data, options) {
142
+ const features = [];
143
+ switch (data.type) {
144
+ case "FeatureCollection":
145
+ for (let i = 0; i < data.features.length; i++) featureToInternal(features, data.features[i], options, i);
146
+ break;
147
+ case "Feature":
148
+ featureToInternal(features, data, options);
149
+ break;
150
+ default: featureToInternal(features, {
151
+ type: "Feature",
152
+ geometry: data,
153
+ properties: void 0
154
+ }, options);
155
+ }
156
+ return features;
157
+ }
158
+ function featureToInternal(features, geojson, options, index, depth = 0) {
159
+ if (!geojson.geometry) return;
160
+ if (depth > MAX_GEOMETRY_COLLECTION_DEPTH) throw new Error("GeometryCollection nesting exceeds supported depth: 1024");
161
+ if (geojson.geometry.type === "GeometryCollection") {
162
+ convertGeometryCollection(features, geojson, geojson.geometry, options, index, depth + 1);
163
+ return;
164
+ }
165
+ if (!geojson.geometry.coordinates?.length) return;
166
+ const id = getFeatureId(geojson, options, index);
167
+ const tolerance = Math.pow(options.tolerance / ((1 << options.maxZoom) * options.extent), 2);
168
+ switch (geojson.geometry.type) {
169
+ case "Point":
170
+ convertPointFeature(features, id, geojson.geometry, geojson.properties);
171
+ return;
172
+ case "MultiPoint":
173
+ convertMultiPointFeature(features, id, geojson.geometry, geojson.properties);
174
+ return;
175
+ case "LineString":
176
+ convertLineStringFeature(features, id, geojson.geometry, tolerance, geojson.properties);
177
+ return;
178
+ case "MultiLineString":
179
+ convertMultiLineStringFeature(features, id, geojson.geometry, tolerance, options, geojson.properties);
180
+ return;
181
+ case "Polygon":
182
+ convertPolygonFeature(features, id, geojson.geometry, tolerance, geojson.properties);
183
+ return;
184
+ case "MultiPolygon":
185
+ convertMultiPolygonFeature(features, id, geojson.geometry, tolerance, geojson.properties);
186
+ return;
187
+ default: throw new Error("Input data is not a valid GeoJSON object.");
188
+ }
189
+ }
190
+ function getFeatureId(geojson, options, index) {
191
+ if (options.promoteId) return geojson.properties?.[options.promoteId];
192
+ if (options.generateId) return index || 0;
193
+ return geojson.id;
194
+ }
195
+ function convertGeometryCollection(features, geojson, geometry, options, index, depth = 0) {
196
+ for (const geom of geometry.geometries) featureToInternal(features, {
197
+ id: geojson.id,
198
+ type: "Feature",
199
+ geometry: geom,
200
+ properties: geojson.properties
201
+ }, options, index, depth);
202
+ }
203
+ function convertPointFeature(features, id, geom, properties) {
204
+ const out = [];
205
+ out.push(projectX(geom.coordinates[0]), projectY(geom.coordinates[1]), 0);
206
+ features.push(createFeature(id, "Point", out, properties));
207
+ }
208
+ function convertMultiPointFeature(features, id, geom, properties) {
209
+ const out = [];
210
+ for (const coords of geom.coordinates) out.push(projectX(coords[0]), projectY(coords[1]), 0);
211
+ features.push(createFeature(id, "MultiPoint", out, properties));
212
+ }
213
+ function convertLineStringFeature(features, id, geom, tolerance, properties) {
214
+ const out = { points: [] };
215
+ convertLine(geom.coordinates, out, tolerance, false);
216
+ features.push(createFeature(id, "LineString", out, properties));
217
+ }
218
+ function convertMultiLineStringFeature(features, id, geom, tolerance, options, properties) {
219
+ if (options.lineMetrics) for (const line of geom.coordinates) {
220
+ const out = { points: [] };
221
+ convertLine(line, out, tolerance, false);
222
+ features.push(createFeature(id, "LineString", out, properties));
223
+ }
224
+ else {
225
+ const out = [];
226
+ convertLines(geom.coordinates, out, tolerance, false);
227
+ features.push(createFeature(id, "MultiLineString", out, properties));
228
+ }
229
+ }
230
+ function convertPolygonFeature(features, id, geom, tolerance, properties) {
231
+ const out = [];
232
+ convertLines(geom.coordinates, out, tolerance, true);
233
+ features.push(createFeature(id, "Polygon", out, properties));
234
+ }
235
+ function convertMultiPolygonFeature(features, id, geom, tolerance, properties) {
236
+ const out = [];
237
+ for (const polygon of geom.coordinates) {
238
+ const polygonOut = [];
239
+ convertLines(polygon, polygonOut, tolerance, true);
240
+ out.push(polygonOut);
241
+ }
242
+ features.push(createFeature(id, "MultiPolygon", out, properties));
243
+ }
244
+ function convertLine(ring, out, tolerance, isPolygon) {
245
+ let x0, y0;
246
+ let size = 0;
247
+ for (let j = 0; j < ring.length; j++) {
248
+ const x = projectX(ring[j][0]);
249
+ const y = projectY(ring[j][1]);
250
+ out.points.push(x, y, 0);
251
+ if (j > 0) if (isPolygon) size += (x0 * y - x * y0) / 2;
252
+ else size += Math.sqrt(Math.pow(x - x0, 2) + Math.pow(y - y0, 2));
253
+ x0 = x;
254
+ y0 = y;
255
+ }
256
+ const last = out.points.length - 3;
257
+ out.points[2] = 1;
258
+ if (tolerance > 0) simplify(out.points, 0, last, tolerance);
259
+ out.points[last + 2] = 1;
260
+ optimizeLineMemory(out);
261
+ out.size = Math.abs(size);
262
+ out.start = 0;
263
+ out.end = out.size;
264
+ }
265
+ function convertLines(rings, out, tolerance, isPolygon) {
266
+ for (let i = 0; i < rings.length; i++) {
267
+ const geom = { points: [] };
268
+ convertLine(rings[i], geom, tolerance, isPolygon);
269
+ out.push(geom);
270
+ }
271
+ }
272
+ /**
273
+ * Convert longitude to spherical mercator in [0..1] range
274
+ */
275
+ function projectX(x) {
276
+ return x / 360 + .5;
277
+ }
278
+ /**
279
+ * Convert latitude to spherical mercator in [0..1] range
280
+ */
281
+ function projectY(y) {
282
+ const sin = Math.sin(y * Math.PI / 180);
283
+ const y2 = .5 - .25 * Math.log((1 + sin) / (1 - sin)) / Math.PI;
284
+ return y2 < 0 ? 0 : y2 > 1 ? 1 : y2;
285
+ }
310
286
 
287
+ //#endregion
288
+ //#region src/deconvert.ts
311
289
  /**
312
- * Converts internal source features back to GeoJSON format.
313
- */
314
- function convertToGeoJSON(source) {
315
- const geojson = {
316
- type: 'FeatureCollection',
317
- features: source.map(feature => featureToGeoJSON(feature))
318
- };
319
- return geojson;
320
- }
321
- /**
322
- * Converts a single internal feature to GeoJSON format.
323
- */
324
- function featureToGeoJSON(feature) {
325
- const geojsonFeature = {
326
- type: 'Feature',
327
- geometry: geometryToGeoJSON(feature),
328
- properties: feature.tags
329
- };
330
- if (feature.id != null) {
331
- geojsonFeature.id = feature.id;
332
- }
333
- return geojsonFeature;
334
- }
335
- /**
336
- * Converts a single internal feature geometry to GeoJSON format.
337
- */
338
- function geometryToGeoJSON(feature) {
339
- const { type, geometry } = feature;
340
- switch (type) {
341
- case 'Point':
342
- return {
343
- type: type,
344
- coordinates: unprojectPoint(geometry[0], geometry[1])
345
- };
346
- case 'MultiPoint':
347
- return {
348
- type: type,
349
- coordinates: unprojectPoints(geometry)
350
- };
351
- case 'LineString':
352
- return {
353
- type: type,
354
- coordinates: unprojectPoints(geometry.points)
355
- };
356
- case 'MultiLineString':
357
- case 'Polygon':
358
- return {
359
- type: type,
360
- coordinates: geometry.map(ring => unprojectPoints(ring.points))
361
- };
362
- case 'MultiPolygon':
363
- return {
364
- type: type,
365
- coordinates: geometry.map(polygon => polygon.map(ring => unprojectPoints(ring.points)))
366
- };
367
- }
368
- }
369
- function unprojectPoints(coords) {
370
- const result = [];
371
- for (let i = 0; i < coords.length; i += 3) {
372
- result.push(unprojectPoint(coords[i], coords[i + 1]));
373
- }
374
- return result;
375
- }
376
- function unprojectPoint(x, y) {
377
- return [unprojectX(x), unprojectY(y)];
378
- }
379
- /**
380
- * Convert spherical mercator in [0..1] range to longitude
381
- */
382
- function unprojectX(x) {
383
- return (x - 0.5) * 360;
384
- }
385
- /**
386
- * Convert spherical mercator in [0..1] range to latitude
387
- */
388
- function unprojectY(y) {
389
- const y2 = (180 - y * 360) * Math.PI / 180;
390
- return 360 * Math.atan(Math.exp(y2)) / Math.PI - 90;
391
- }
290
+ * Converts internal source features back to GeoJSON format.
291
+ */
292
+ function convertToGeoJSON(source) {
293
+ return {
294
+ type: "FeatureCollection",
295
+ features: source.map((feature) => featureToGeoJSON(feature))
296
+ };
297
+ }
298
+ /**
299
+ * Converts a single internal feature to GeoJSON format.
300
+ */
301
+ function featureToGeoJSON(feature) {
302
+ const geojsonFeature = {
303
+ type: "Feature",
304
+ geometry: geometryToGeoJSON(feature),
305
+ properties: feature.tags
306
+ };
307
+ if (feature.id != null) geojsonFeature.id = feature.id;
308
+ return geojsonFeature;
309
+ }
310
+ /**
311
+ * Converts a single internal feature geometry to GeoJSON format.
312
+ */
313
+ function geometryToGeoJSON(feature) {
314
+ const { type, geometry } = feature;
315
+ switch (type) {
316
+ case "Point": return {
317
+ type,
318
+ coordinates: unprojectPoint(geometry[0], geometry[1])
319
+ };
320
+ case "MultiPoint": return {
321
+ type,
322
+ coordinates: unprojectPoints(geometry)
323
+ };
324
+ case "LineString": return {
325
+ type,
326
+ coordinates: unprojectPoints(geometry.points)
327
+ };
328
+ case "MultiLineString":
329
+ case "Polygon": return {
330
+ type,
331
+ coordinates: geometry.map((ring) => unprojectPoints(ring.points))
332
+ };
333
+ case "MultiPolygon": return {
334
+ type,
335
+ coordinates: geometry.map((polygon) => polygon.map((ring) => unprojectPoints(ring.points)))
336
+ };
337
+ }
338
+ }
339
+ function unprojectPoints(coords) {
340
+ const result = [];
341
+ for (let i = 0; i < coords.length; i += 3) result.push(unprojectPoint(coords[i], coords[i + 1]));
342
+ return result;
343
+ }
344
+ function unprojectPoint(x, y) {
345
+ return [unprojectX(x), unprojectY(y)];
346
+ }
347
+ /**
348
+ * Convert spherical mercator in [0..1] range to longitude
349
+ */
350
+ function unprojectX(x) {
351
+ return (x - .5) * 360;
352
+ }
353
+ /**
354
+ * Convert spherical mercator in [0..1] range to latitude
355
+ */
356
+ function unprojectY(y) {
357
+ const y2 = (180 - y * 360) * Math.PI / 180;
358
+ return 360 * Math.atan(Math.exp(y2)) / Math.PI - 90;
359
+ }
392
360
 
393
- var AxisType;
394
- (function (AxisType) {
395
- AxisType[AxisType["X"] = 0] = "X";
396
- AxisType[AxisType["Y"] = 1] = "Y";
397
- })(AxisType || (AxisType = {}));
398
- /**
399
- * clip features between two vertical or horizontal axis-parallel lines:
400
- * | |
401
- * ___|___ | /
402
- * / | \____|____/
403
- * | |
404
- *
405
- * @param features - the features to clip
406
- * @param scale - the scale to divide start and end inputs
407
- * @param start - the start of the clip range
408
- * @param end - the end of the clip range
409
- * @param axis - which axis to clip against
410
- * @param minAll - the minimum for all features in the relevant axis
411
- * @param maxAll - the maximum for all features in the relevant axis
412
- */
413
- function clip(features, scale, start, end, axis, minAll, maxAll, options) {
414
- start /= scale;
415
- end /= scale;
416
- if (minAll >= start && maxAll < end) { // trivial accept
417
- return features;
418
- }
419
- if (maxAll < start || minAll >= end) { // trivial reject
420
- return null;
421
- }
422
- const clipped = [];
423
- for (const feature of features) {
424
- const min = axis === AxisType.X ? feature.minX : feature.minY;
425
- const max = axis === AxisType.X ? feature.maxX : feature.maxY;
426
- if (min >= start && max < end) { // trivial accept
427
- clipped.push(feature);
428
- continue;
429
- }
430
- if (max < start || min >= end) { // trivial reject
431
- continue;
432
- }
433
- switch (feature.type) {
434
- case 'Point':
435
- case 'MultiPoint': {
436
- clipPointFeature(feature, clipped, start, end, axis);
437
- continue;
438
- }
439
- case 'LineString': {
440
- clipLineStringFeature(feature, clipped, start, end, axis, options);
441
- continue;
442
- }
443
- case 'MultiLineString': {
444
- clipMultiLineStringFeature(feature, clipped, start, end, axis);
445
- continue;
446
- }
447
- case 'Polygon': {
448
- clipPolygonFeature(feature, clipped, start, end, axis);
449
- continue;
450
- }
451
- case 'MultiPolygon': {
452
- clipMultiPolygonFeature(feature, clipped, start, end, axis);
453
- continue;
454
- }
455
- }
456
- }
457
- if (!clipped.length)
458
- return null;
459
- return clipped;
460
- }
461
- function clipPointFeature(feature, clipped, start, end, axis) {
462
- const geom = [];
463
- clipPoints(feature.geometry, geom, start, end, axis);
464
- if (!geom.length)
465
- return;
466
- const type = geom.length === 3 ? 'Point' : 'MultiPoint';
467
- clipped.push(createFeature(feature.id, type, geom, feature.tags));
468
- }
469
- function clipLineStringFeature(feature, clipped, start, end, axis, options) {
470
- const geom = [];
471
- clipLine(feature.geometry, geom, start, end, axis, false, options.lineMetrics);
472
- if (!geom.length)
473
- return;
474
- if (options.lineMetrics) {
475
- for (const line of geom) {
476
- clipped.push(createFeature(feature.id, 'LineString', line, feature.tags));
477
- }
478
- return;
479
- }
480
- if (geom.length > 1) {
481
- clipped.push(createFeature(feature.id, 'MultiLineString', geom, feature.tags));
482
- return;
483
- }
484
- clipped.push(createFeature(feature.id, 'LineString', geom[0], feature.tags));
485
- }
486
- function clipMultiLineStringFeature(feature, clipped, start, end, axis) {
487
- const geom = [];
488
- clipLines(feature.geometry, geom, start, end, axis, false);
489
- if (!geom.length)
490
- return;
491
- if (geom.length === 1) {
492
- clipped.push(createFeature(feature.id, 'LineString', geom[0], feature.tags));
493
- return;
494
- }
495
- clipped.push(createFeature(feature.id, 'MultiLineString', geom, feature.tags));
496
- }
497
- function clipPolygonFeature(feature, clipped, start, end, axis) {
498
- const geom = [];
499
- clipLines(feature.geometry, geom, start, end, axis, true);
500
- if (!geom.length)
501
- return;
502
- clipped.push(createFeature(feature.id, 'Polygon', geom, feature.tags));
503
- }
504
- function clipMultiPolygonFeature(feature, clipped, start, end, axis) {
505
- const geom = [];
506
- for (const polygon of feature.geometry) {
507
- const newPolygon = [];
508
- clipLines(polygon, newPolygon, start, end, axis, true);
509
- if (!newPolygon.length)
510
- continue;
511
- geom.push(newPolygon);
512
- }
513
- if (!geom.length)
514
- return;
515
- clipped.push(createFeature(feature.id, 'MultiPolygon', geom, feature.tags));
516
- }
517
- function clipPoints(geom, newGeom, start, end, axis) {
518
- for (let i = 0; i < geom.length; i += 3) {
519
- const a = geom[i + axis];
520
- if (a >= start && a <= end) {
521
- addPoint(newGeom, geom[i], geom[i + 1], geom[i + 2]);
522
- }
523
- }
524
- }
525
- function clipLine(geom, newGeom, start, end, axis, isPolygon, trackMetrics) {
526
- let slice = newSlice(geom);
527
- const intersect = axis === AxisType.X ? intersectX : intersectY;
528
- let len = geom.start;
529
- let segLen, t;
530
- for (let i = 0; i < geom.points.length - 3; i += 3) {
531
- const ax = geom.points[i];
532
- const ay = geom.points[i + 1];
533
- const az = geom.points[i + 2];
534
- const bx = geom.points[i + 3];
535
- const by = geom.points[i + 4];
536
- const a = axis === AxisType.X ? ax : ay;
537
- const b = axis === AxisType.X ? bx : by;
538
- let exited = false;
539
- if (trackMetrics)
540
- segLen = Math.sqrt(Math.pow(ax - bx, 2) + Math.pow(ay - by, 2));
541
- if (a < start) {
542
- // ---|--> | (line enters the clip region from the left)
543
- if (b > start) {
544
- t = intersect(slice, ax, ay, bx, by, start);
545
- if (trackMetrics)
546
- slice.start = len + segLen * t;
547
- }
548
- }
549
- else if (a > end) {
550
- // | <--|--- (line enters the clip region from the right)
551
- if (b < end) {
552
- t = intersect(slice, ax, ay, bx, by, end);
553
- if (trackMetrics)
554
- slice.start = len + segLen * t;
555
- }
556
- }
557
- else {
558
- addPoint(slice.points, ax, ay, az);
559
- }
560
- if (b < start && a >= start) {
561
- // <--|--- | or <--|-----|--- (line exits the clip region on the left)
562
- t = intersect(slice, ax, ay, bx, by, start);
563
- exited = true;
564
- }
565
- if (b > end && a <= end) {
566
- // | ---|--> or ---|-----|--> (line exits the clip region on the right)
567
- t = intersect(slice, ax, ay, bx, by, end);
568
- exited = true;
569
- }
570
- if (!isPolygon && exited) {
571
- if (trackMetrics)
572
- slice.end = len + segLen * t;
573
- newGeom.push(slice);
574
- slice = newSlice(geom);
575
- }
576
- if (trackMetrics)
577
- len += segLen;
578
- }
579
- // add the last point
580
- let last = geom.points.length - 3;
581
- const ax = geom.points[last];
582
- const ay = geom.points[last + 1];
583
- const az = geom.points[last + 2];
584
- const a = axis === AxisType.X ? ax : ay;
585
- if (a >= start && a <= end)
586
- addPoint(slice.points, ax, ay, az);
587
- // close the polygon if its endpoints are not the same after clipping
588
- last = slice.points.length - 3;
589
- if (isPolygon && last >= 3 && (slice.points[last] !== slice.points[0] || slice.points[last + 1] !== slice.points[1])) {
590
- addPoint(slice.points, slice.points[0], slice.points[1], slice.points[2]);
591
- }
592
- // add the final slice
593
- if (slice.points.length) {
594
- optimizeLineMemory(slice);
595
- newGeom.push(slice);
596
- }
597
- }
598
- function newSlice(line) {
599
- return {
600
- points: [],
601
- size: line.size,
602
- start: line.start,
603
- end: line.end
604
- };
605
- }
606
- function clipLines(geom, newGeom, start, end, axis, isPolygon) {
607
- for (const line of geom) {
608
- clipLine(line, newGeom, start, end, axis, isPolygon, false);
609
- }
610
- }
611
- function addPoint(out, x, y, z) {
612
- out.push(x, y, z);
613
- }
614
- function intersectX(out, ax, ay, bx, by, x) {
615
- const t = (x - ax) / (bx - ax);
616
- addPoint(out.points, x, ay + (by - ay) * t, 1);
617
- return t;
618
- }
619
- function intersectY(out, ax, ay, bx, by, y) {
620
- const t = (y - ay) / (by - ay);
621
- addPoint(out.points, ax + (bx - ax) * t, y, 1);
622
- return t;
623
- }
361
+ //#endregion
362
+ //#region src/clip.ts
363
+ /**
364
+ * clip features between two vertical or horizontal axis-parallel lines:
365
+ * | |
366
+ * ___|___ | /
367
+ * / | \____|____/
368
+ * | |
369
+ *
370
+ * @param features - the features to clip
371
+ * @param scale - the scale to divide start and end inputs
372
+ * @param start - the start of the clip range
373
+ * @param end - the end of the clip range
374
+ * @param axis - which axis to clip against
375
+ * @param minAll - the minimum for all features in the relevant axis
376
+ * @param maxAll - the maximum for all features in the relevant axis
377
+ */
378
+ function clip(features, scale, start, end, axis, minAll, maxAll, options) {
379
+ start /= scale;
380
+ end /= scale;
381
+ if (minAll >= start && maxAll < end) return features;
382
+ if (maxAll < start || minAll >= end) return null;
383
+ const clipped = [];
384
+ for (const feature of features) {
385
+ const min = axis === 0 ? feature.minX : feature.minY;
386
+ const max = axis === 0 ? feature.maxX : feature.maxY;
387
+ if (min >= start && max < end) {
388
+ clipped.push(feature);
389
+ continue;
390
+ }
391
+ if (max < start || min >= end) continue;
392
+ switch (feature.type) {
393
+ case "Point":
394
+ case "MultiPoint":
395
+ clipPointFeature(feature, clipped, start, end, axis);
396
+ continue;
397
+ case "LineString":
398
+ clipLineStringFeature(feature, clipped, start, end, axis, options);
399
+ continue;
400
+ case "MultiLineString":
401
+ clipMultiLineStringFeature(feature, clipped, start, end, axis);
402
+ continue;
403
+ case "Polygon":
404
+ clipPolygonFeature(feature, clipped, start, end, axis);
405
+ continue;
406
+ case "MultiPolygon":
407
+ clipMultiPolygonFeature(feature, clipped, start, end, axis);
408
+ continue;
409
+ }
410
+ }
411
+ if (!clipped.length) return null;
412
+ return clipped;
413
+ }
414
+ function clipPointFeature(feature, clipped, start, end, axis) {
415
+ const geom = [];
416
+ clipPoints(feature.geometry, geom, start, end, axis);
417
+ if (!geom.length) return;
418
+ const type = geom.length === 3 ? "Point" : "MultiPoint";
419
+ clipped.push(createFeature(feature.id, type, geom, feature.tags));
420
+ }
421
+ function clipLineStringFeature(feature, clipped, start, end, axis, options) {
422
+ const geom = [];
423
+ clipLine(feature.geometry, geom, start, end, axis, false, options.lineMetrics);
424
+ if (!geom.length) return;
425
+ if (options.lineMetrics) {
426
+ for (const line of geom) clipped.push(createFeature(feature.id, "LineString", line, feature.tags));
427
+ return;
428
+ }
429
+ if (geom.length > 1) {
430
+ clipped.push(createFeature(feature.id, "MultiLineString", geom, feature.tags));
431
+ return;
432
+ }
433
+ clipped.push(createFeature(feature.id, "LineString", geom[0], feature.tags));
434
+ }
435
+ function clipMultiLineStringFeature(feature, clipped, start, end, axis) {
436
+ const geom = [];
437
+ clipLines(feature.geometry, geom, start, end, axis, false);
438
+ if (!geom.length) return;
439
+ if (geom.length === 1) {
440
+ clipped.push(createFeature(feature.id, "LineString", geom[0], feature.tags));
441
+ return;
442
+ }
443
+ clipped.push(createFeature(feature.id, "MultiLineString", geom, feature.tags));
444
+ }
445
+ function clipPolygonFeature(feature, clipped, start, end, axis) {
446
+ const geom = [];
447
+ clipLines(feature.geometry, geom, start, end, axis, true);
448
+ if (!geom.length) return;
449
+ clipped.push(createFeature(feature.id, "Polygon", geom, feature.tags));
450
+ }
451
+ function clipMultiPolygonFeature(feature, clipped, start, end, axis) {
452
+ const geom = [];
453
+ for (const polygon of feature.geometry) {
454
+ const newPolygon = [];
455
+ clipLines(polygon, newPolygon, start, end, axis, true);
456
+ if (!newPolygon.length) continue;
457
+ geom.push(newPolygon);
458
+ }
459
+ if (!geom.length) return;
460
+ clipped.push(createFeature(feature.id, "MultiPolygon", geom, feature.tags));
461
+ }
462
+ function clipPoints(geom, newGeom, start, end, axis) {
463
+ for (let i = 0; i < geom.length; i += 3) {
464
+ const a = geom[i + axis];
465
+ if (a >= start && a <= end) addPoint(newGeom, geom[i], geom[i + 1], geom[i + 2]);
466
+ }
467
+ }
468
+ function clipLine(geom, newGeom, start, end, axis, isPolygon, trackMetrics) {
469
+ let slice = newSlice(geom);
470
+ const intersect = axis === 0 ? intersectX : intersectY;
471
+ let len = geom.start;
472
+ let segLen, t;
473
+ for (let i = 0; i < geom.points.length - 3; i += 3) {
474
+ const ax = geom.points[i];
475
+ const ay = geom.points[i + 1];
476
+ const az = geom.points[i + 2];
477
+ const bx = geom.points[i + 3];
478
+ const by = geom.points[i + 4];
479
+ const a = axis === 0 ? ax : ay;
480
+ const b = axis === 0 ? bx : by;
481
+ let exited = false;
482
+ if (trackMetrics) segLen = Math.sqrt(Math.pow(ax - bx, 2) + Math.pow(ay - by, 2));
483
+ if (a < start) {
484
+ if (b > start) {
485
+ t = intersect(slice, ax, ay, bx, by, start);
486
+ if (trackMetrics) slice.start = len + segLen * t;
487
+ }
488
+ } else if (a > end) {
489
+ if (b < end) {
490
+ t = intersect(slice, ax, ay, bx, by, end);
491
+ if (trackMetrics) slice.start = len + segLen * t;
492
+ }
493
+ } else addPoint(slice.points, ax, ay, az);
494
+ if (b < start && a >= start) {
495
+ t = intersect(slice, ax, ay, bx, by, start);
496
+ exited = true;
497
+ }
498
+ if (b > end && a <= end) {
499
+ t = intersect(slice, ax, ay, bx, by, end);
500
+ exited = true;
501
+ }
502
+ if (!isPolygon && exited) {
503
+ if (trackMetrics) slice.end = len + segLen * t;
504
+ newGeom.push(slice);
505
+ slice = newSlice(geom);
506
+ }
507
+ if (trackMetrics) len += segLen;
508
+ }
509
+ let last = geom.points.length - 3;
510
+ const ax = geom.points[last];
511
+ const ay = geom.points[last + 1];
512
+ const az = geom.points[last + 2];
513
+ const a = axis === 0 ? ax : ay;
514
+ if (a >= start && a <= end) addPoint(slice.points, ax, ay, az);
515
+ last = slice.points.length - 3;
516
+ if (isPolygon && last >= 3 && (slice.points[last] !== slice.points[0] || slice.points[last + 1] !== slice.points[1])) addPoint(slice.points, slice.points[0], slice.points[1], slice.points[2]);
517
+ if (slice.points.length) {
518
+ optimizeLineMemory(slice);
519
+ newGeom.push(slice);
520
+ }
521
+ }
522
+ function newSlice(line) {
523
+ return {
524
+ points: [],
525
+ size: line.size,
526
+ start: line.start,
527
+ end: line.end
528
+ };
529
+ }
530
+ function clipLines(geom, newGeom, start, end, axis, isPolygon) {
531
+ for (const line of geom) clipLine(line, newGeom, start, end, axis, isPolygon, false);
532
+ }
533
+ function addPoint(out, x, y, z) {
534
+ out.push(x, y, z);
535
+ }
536
+ function intersectX(out, ax, ay, bx, by, x) {
537
+ const t = (x - ax) / (bx - ax);
538
+ addPoint(out.points, x, ay + (by - ay) * t, 1);
539
+ return t;
540
+ }
541
+ function intersectY(out, ax, ay, bx, by, y) {
542
+ const t = (y - ay) / (by - ay);
543
+ addPoint(out.points, ax + (bx - ax) * t, y, 1);
544
+ return t;
545
+ }
624
546
 
625
- function wrap(features, options) {
626
- const buffer = options.buffer / options.extent;
627
- let merged = features;
628
- const left = clip(features, 1, -1 - buffer, buffer, AxisType.X, -1, 2, options); // left world copy
629
- const right = clip(features, 1, 1 - buffer, 2 + buffer, AxisType.X, -1, 2, options); // right world copy
630
- if (!left && !right)
631
- return merged;
632
- merged = clip(features, 1, -buffer, 1 + buffer, AxisType.X, -1, 2, options) || []; // center world copy
633
- if (left)
634
- merged = shiftFeatureCoords(left, 1).concat(merged); // merge left into center
635
- if (right)
636
- merged = merged.concat(shiftFeatureCoords(right, -1)); // merge right into center
637
- return merged;
638
- }
639
- function shiftFeatureCoords(features, offset) {
640
- const newFeatures = [];
641
- for (const feature of features) {
642
- switch (feature.type) {
643
- case 'Point':
644
- case 'MultiPoint': {
645
- const newGeometry = shiftPointCoords(feature.geometry, offset);
646
- newFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags));
647
- continue;
648
- }
649
- case 'LineString': {
650
- const newGeometry = shiftLineCoords(feature.geometry, offset);
651
- newFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags));
652
- continue;
653
- }
654
- case 'MultiLineString':
655
- case 'Polygon': {
656
- const newGeometry = [];
657
- for (const line of feature.geometry) {
658
- newGeometry.push(shiftLineCoords(line, offset));
659
- }
660
- newFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags));
661
- continue;
662
- }
663
- case 'MultiPolygon': {
664
- const newGeometry = [];
665
- for (const polygon of feature.geometry) {
666
- const newPolygon = [];
667
- for (const line of polygon) {
668
- newPolygon.push(shiftLineCoords(line, offset));
669
- }
670
- newGeometry.push(newPolygon);
671
- }
672
- newFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags));
673
- continue;
674
- }
675
- }
676
- }
677
- return newFeatures;
678
- }
679
- function shiftPointCoords(coords, offset) {
680
- const newCoords = [];
681
- for (let i = 0; i < coords.length; i += 3) {
682
- newCoords.push(coords[i] + offset, coords[i + 1], coords[i + 2]);
683
- }
684
- return newCoords;
685
- }
686
- function shiftLineCoords(line, offset) {
687
- const newLine = {
688
- points: [],
689
- size: line.size
690
- };
691
- if (line.start !== undefined) {
692
- newLine.start = line.start;
693
- newLine.end = line.end;
694
- }
695
- for (let i = 0; i < line.points.length; i += 3) {
696
- newLine.points.push(line.points[i] + offset, line.points[i + 1], line.points[i + 2]);
697
- }
698
- optimizeLineMemory(newLine);
699
- return newLine;
700
- }
547
+ //#endregion
548
+ //#region src/wrap.ts
549
+ function wrap(features, options) {
550
+ const buffer = options.buffer / options.extent;
551
+ let merged = features;
552
+ const left = clip(features, 1, -1 - buffer, buffer, 0, -1, 2, options);
553
+ const right = clip(features, 1, 1 - buffer, 2 + buffer, 0, -1, 2, options);
554
+ if (!left && !right) return merged;
555
+ merged = clip(features, 1, -buffer, 1 + buffer, 0, -1, 2, options) || [];
556
+ if (left) merged = shiftFeatureCoords(left, 1).concat(merged);
557
+ if (right) merged = merged.concat(shiftFeatureCoords(right, -1));
558
+ return merged;
559
+ }
560
+ function shiftFeatureCoords(features, offset) {
561
+ const newFeatures = [];
562
+ for (const feature of features) switch (feature.type) {
563
+ case "Point":
564
+ case "MultiPoint": {
565
+ const newGeometry = shiftPointCoords(feature.geometry, offset);
566
+ newFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags));
567
+ continue;
568
+ }
569
+ case "LineString": {
570
+ const newGeometry = shiftLineCoords(feature.geometry, offset);
571
+ newFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags));
572
+ continue;
573
+ }
574
+ case "MultiLineString":
575
+ case "Polygon": {
576
+ const newGeometry = [];
577
+ for (const line of feature.geometry) newGeometry.push(shiftLineCoords(line, offset));
578
+ newFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags));
579
+ continue;
580
+ }
581
+ case "MultiPolygon": {
582
+ const newGeometry = [];
583
+ for (const polygon of feature.geometry) {
584
+ const newPolygon = [];
585
+ for (const line of polygon) newPolygon.push(shiftLineCoords(line, offset));
586
+ newGeometry.push(newPolygon);
587
+ }
588
+ newFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags));
589
+ continue;
590
+ }
591
+ }
592
+ return newFeatures;
593
+ }
594
+ function shiftPointCoords(coords, offset) {
595
+ const newCoords = [];
596
+ for (let i = 0; i < coords.length; i += 3) newCoords.push(coords[i] + offset, coords[i + 1], coords[i + 2]);
597
+ return newCoords;
598
+ }
599
+ function shiftLineCoords(line, offset) {
600
+ const newLine = {
601
+ points: [],
602
+ size: line.size
603
+ };
604
+ if (line.start !== void 0) {
605
+ newLine.start = line.start;
606
+ newLine.end = line.end;
607
+ }
608
+ for (let i = 0; i < line.points.length; i += 3) newLine.points.push(line.points[i] + offset, line.points[i + 1], line.points[i + 2]);
609
+ optimizeLineMemory(newLine);
610
+ return newLine;
611
+ }
701
612
 
613
+ //#endregion
614
+ //#region src/difference.ts
702
615
  /**
703
- * Applies a GeoJSON Source Diff to an existing set of simplified features
704
- * @param source
705
- * @param dataDiff
706
- * @param options
707
- * @returns
708
- */
709
- function applySourceDiff(source, dataDiff, options) {
710
- // convert diff to sets/maps for o(1) lookups
711
- const diff = diffToHashed(dataDiff, options);
712
- // collection for features that will be affected by this update and used to invalidate tiles
713
- let affected = [];
714
- if (diff.removeAll) {
715
- affected = source;
716
- source = [];
717
- }
718
- if (diff.remove.size || diff.add.size) {
719
- const removeFeatures = [];
720
- // Collect features to remove (explicit removals + replacements via add)
721
- for (const feature of source) {
722
- if (diff.remove.has(feature.id) || diff.add.has(feature.id)) {
723
- removeFeatures.push(feature);
724
- }
725
- }
726
- if (removeFeatures.length) {
727
- affected.push(...removeFeatures);
728
- const removeIds = new Set(removeFeatures.map(f => f.id));
729
- source = source.filter(f => !removeIds.has(f.id));
730
- }
731
- if (diff.add.size) {
732
- let addFeatures = convertToInternal({ type: 'FeatureCollection', features: Array.from(diff.add.values()) }, options);
733
- addFeatures = wrap(addFeatures, options);
734
- affected.push(...addFeatures);
735
- source.push(...addFeatures);
736
- }
737
- }
738
- if (diff.update.size) {
739
- // Features can be duplicated across the antimeridian (wrap) in a single tile, so must update all instances with the same id
740
- const oldFeaturesMap = new Map();
741
- const keepFeatures = [];
742
- for (const feature of source) {
743
- if (diff.update.has(feature.id)) {
744
- oldFeaturesMap.set(feature.id, [...(oldFeaturesMap.get(feature.id) || []), feature]);
745
- }
746
- else {
747
- keepFeatures.push(feature);
748
- }
749
- }
750
- for (const [id, update] of diff.update) {
751
- const oldFeatures = oldFeaturesMap.get(id);
752
- if (!oldFeatures || oldFeatures.length === 0)
753
- continue;
754
- const updatedFeatures = getUpdatedFeatures(oldFeatures, update, options);
755
- affected.push(...oldFeatures, ...updatedFeatures);
756
- keepFeatures.push(...updatedFeatures);
757
- }
758
- source = keepFeatures;
759
- }
760
- return { affected, source };
761
- }
762
- /**
763
- * Gets updated simplified feature(s) based on a diff update object.
764
- * @param vtFeatures - the original features
765
- * @param update - the update object to apply
766
- * @param options - the options to use for the wrap method
767
- * @returns Updated features. If geometry is updated, returns new feature(s) converted from geojson and wrapped. If only properties are updated, returns feature(s) with tags updated.
768
- */
769
- function getUpdatedFeatures(vtFeatures, update, options) {
770
- const changeGeometry = !!update.newGeometry;
771
- const changeProps = update.removeAllProperties ||
772
- update.removeProperties?.length > 0 ||
773
- update.addOrUpdateProperties?.length > 0;
774
- // if geometry changed, need to create a new geojson feature and convert to internal format
775
- if (changeGeometry) {
776
- const vtFeature = vtFeatures[0];
777
- const geojsonFeature = {
778
- type: 'Feature',
779
- id: vtFeature.id,
780
- geometry: update.newGeometry,
781
- properties: changeProps ? applyPropertyUpdates(vtFeature.tags, update) : vtFeature.tags
782
- };
783
- let features = convertToInternal({ type: 'FeatureCollection', features: [geojsonFeature] }, options);
784
- features = wrap(features, options);
785
- return features;
786
- }
787
- if (changeProps) {
788
- const updated = [];
789
- for (const vtFeature of vtFeatures) {
790
- const feature = { ...vtFeature };
791
- feature.tags = applyPropertyUpdates(feature.tags, update);
792
- updated.push(feature);
793
- }
794
- return updated;
795
- }
796
- return vtFeatures;
797
- }
798
- /**
799
- * helper to apply property updates from a diff update object to a properties object
800
- */
801
- function applyPropertyUpdates(tags, update) {
802
- if (update.removeAllProperties) {
803
- return {};
804
- }
805
- const properties = { ...tags || {} };
806
- if (update.removeProperties) {
807
- for (const key of update.removeProperties) {
808
- delete properties[key];
809
- }
810
- }
811
- if (update.addOrUpdateProperties) {
812
- for (const { key, value } of update.addOrUpdateProperties) {
813
- properties[key] = value;
814
- }
815
- }
816
- return properties;
817
- }
818
- /**
819
- * Convert a GeoJSON Source Diff to an idempotent hashed representation using Sets and Maps
820
- */
821
- function diffToHashed(diff, options) {
822
- if (!diff)
823
- return {
824
- remove: new Set(),
825
- add: new Map(),
826
- update: new Map()
827
- };
828
- const hashed = {
829
- removeAll: diff.removeAll,
830
- remove: new Set(diff.remove || []),
831
- add: new Map(diff.add?.map(feature => [options.promoteId ? feature.properties[options.promoteId] : feature.id, feature])),
832
- update: new Map(diff.update?.map(update => [update.id, update]))
833
- };
834
- return hashed;
835
- }
836
-
837
- const ARRAY_TYPES = [
838
- Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array,
839
- Int32Array, Uint32Array, Float32Array, Float64Array
840
- ];
841
-
842
- /** @typedef {Int8ArrayConstructor | Uint8ArrayConstructor | Uint8ClampedArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor} TypedArrayConstructor */
843
-
844
- const VERSION = 1; // serialized format version
845
- const HEADER_SIZE = 8;
846
-
847
- class KDBush {
848
-
849
- /**
850
- * Creates an index from raw `ArrayBuffer` data.
851
- * @param {ArrayBuffer} data
852
- */
853
- static from(data) {
854
- if (!(data instanceof ArrayBuffer)) {
855
- throw new Error('Data must be an instance of ArrayBuffer.');
856
- }
857
- const [magic, versionAndType] = new Uint8Array(data, 0, 2);
858
- if (magic !== 0xdb) {
859
- throw new Error('Data does not appear to be in a KDBush format.');
860
- }
861
- const version = versionAndType >> 4;
862
- if (version !== VERSION) {
863
- throw new Error(`Got v${version} data when expected v${VERSION}.`);
864
- }
865
- const ArrayType = ARRAY_TYPES[versionAndType & 0x0f];
866
- if (!ArrayType) {
867
- throw new Error('Unrecognized array type.');
868
- }
869
- const [nodeSize] = new Uint16Array(data, 2, 1);
870
- const [numItems] = new Uint32Array(data, 4, 1);
871
-
872
- return new KDBush(numItems, nodeSize, ArrayType, data);
873
- }
874
-
875
- /**
876
- * Creates an index that will hold a given number of items.
877
- * @param {number} numItems
878
- * @param {number} [nodeSize=64] Size of the KD-tree node (64 by default).
879
- * @param {TypedArrayConstructor} [ArrayType=Float64Array] The array type used for coordinates storage (`Float64Array` by default).
880
- * @param {ArrayBuffer} [data] (For internal use only)
881
- */
882
- constructor(numItems, nodeSize = 64, ArrayType = Float64Array, data) {
883
- if (isNaN(numItems) || numItems < 0) throw new Error(`Unpexpected numItems value: ${numItems}.`);
884
-
885
- this.numItems = +numItems;
886
- this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535);
887
- this.ArrayType = ArrayType;
888
- this.IndexArrayType = numItems < 65536 ? Uint16Array : Uint32Array;
889
-
890
- const arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType);
891
- const coordsByteSize = numItems * 2 * this.ArrayType.BYTES_PER_ELEMENT;
892
- const idsByteSize = numItems * this.IndexArrayType.BYTES_PER_ELEMENT;
893
- const padCoords = (8 - idsByteSize % 8) % 8;
894
-
895
- if (arrayTypeIndex < 0) {
896
- throw new Error(`Unexpected typed array class: ${ArrayType}.`);
897
- }
898
-
899
- if (data && (data instanceof ArrayBuffer)) { // reconstruct an index from a buffer
900
- this.data = data;
901
- this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems);
902
- this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);
903
- this._pos = numItems * 2;
904
- this._finished = true;
905
- } else { // initialize a new index
906
- this.data = new ArrayBuffer(HEADER_SIZE + coordsByteSize + idsByteSize + padCoords);
907
- this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems);
908
- this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);
909
- this._pos = 0;
910
- this._finished = false;
911
-
912
- // set header
913
- new Uint8Array(this.data, 0, 2).set([0xdb, (VERSION << 4) + arrayTypeIndex]);
914
- new Uint16Array(this.data, 2, 1)[0] = nodeSize;
915
- new Uint32Array(this.data, 4, 1)[0] = numItems;
916
- }
917
- }
918
-
919
- /**
920
- * Add a point to the index.
921
- * @param {number} x
922
- * @param {number} y
923
- * @returns {number} An incremental index associated with the added item (starting from `0`).
924
- */
925
- add(x, y) {
926
- const index = this._pos >> 1;
927
- this.ids[index] = index;
928
- this.coords[this._pos++] = x;
929
- this.coords[this._pos++] = y;
930
- return index;
931
- }
932
-
933
- /**
934
- * Perform indexing of the added points.
935
- */
936
- finish() {
937
- const numAdded = this._pos >> 1;
938
- if (numAdded !== this.numItems) {
939
- throw new Error(`Added ${numAdded} items when expected ${this.numItems}.`);
940
- }
941
- // kd-sort both arrays for efficient search
942
- sort(this.ids, this.coords, this.nodeSize, 0, this.numItems - 1, 0);
943
-
944
- this._finished = true;
945
- return this;
946
- }
947
-
948
- /**
949
- * Search the index for items within a given bounding box.
950
- * @param {number} minX
951
- * @param {number} minY
952
- * @param {number} maxX
953
- * @param {number} maxY
954
- * @returns {number[]} An array of indices correponding to the found items.
955
- */
956
- range(minX, minY, maxX, maxY) {
957
- if (!this._finished) throw new Error('Data not yet indexed - call index.finish().');
958
-
959
- const {ids, coords, nodeSize} = this;
960
- const stack = [0, ids.length - 1, 0];
961
- const result = [];
962
-
963
- // recursively search for items in range in the kd-sorted arrays
964
- while (stack.length) {
965
- const axis = stack.pop() || 0;
966
- const right = stack.pop() || 0;
967
- const left = stack.pop() || 0;
968
-
969
- // if we reached "tree node", search linearly
970
- if (right - left <= nodeSize) {
971
- for (let i = left; i <= right; i++) {
972
- const x = coords[2 * i];
973
- const y = coords[2 * i + 1];
974
- if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[i]);
975
- }
976
- continue;
977
- }
978
-
979
- // otherwise find the middle index
980
- const m = (left + right) >> 1;
981
-
982
- // include the middle item if it's in range
983
- const x = coords[2 * m];
984
- const y = coords[2 * m + 1];
985
- if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]);
986
-
987
- // queue search in halves that intersect the query
988
- if (axis === 0 ? minX <= x : minY <= y) {
989
- stack.push(left);
990
- stack.push(m - 1);
991
- stack.push(1 - axis);
992
- }
993
- if (axis === 0 ? maxX >= x : maxY >= y) {
994
- stack.push(m + 1);
995
- stack.push(right);
996
- stack.push(1 - axis);
997
- }
998
- }
616
+ * Applies a GeoJSON Source Diff to an existing set of simplified features
617
+ * @param source
618
+ * @param dataDiff
619
+ * @param options
620
+ * @returns
621
+ */
622
+ function applySourceDiff(source, dataDiff, options) {
623
+ const diff = diffToHashed(dataDiff, options);
624
+ let affected = [];
625
+ if (diff.removeAll) {
626
+ affected = source;
627
+ source = [];
628
+ }
629
+ if (diff.remove.size || diff.add.size) {
630
+ const removeFeatures = [];
631
+ for (const feature of source) if (diff.remove.has(feature.id) || diff.add.has(feature.id)) removeFeatures.push(feature);
632
+ if (removeFeatures.length) {
633
+ affected = affected.concat(removeFeatures);
634
+ const removeIds = new Set(removeFeatures.map((f) => f.id));
635
+ source = source.filter((f) => !removeIds.has(f.id));
636
+ }
637
+ if (diff.add.size) {
638
+ let addFeatures = convertToInternal({
639
+ type: "FeatureCollection",
640
+ features: Array.from(diff.add.values())
641
+ }, options);
642
+ addFeatures = wrap(addFeatures, options);
643
+ affected = affected.concat(addFeatures);
644
+ source = source.concat(addFeatures);
645
+ }
646
+ }
647
+ if (diff.update.size) {
648
+ const oldFeaturesMap = /* @__PURE__ */ new Map();
649
+ let keepFeatures = [];
650
+ for (const feature of source) if (diff.update.has(feature.id)) oldFeaturesMap.set(feature.id, [...oldFeaturesMap.get(feature.id) || [], feature]);
651
+ else keepFeatures.push(feature);
652
+ for (const [id, update] of diff.update) {
653
+ const oldFeatures = oldFeaturesMap.get(id);
654
+ if (!oldFeatures || oldFeatures.length === 0) continue;
655
+ const updatedFeatures = getUpdatedFeatures(oldFeatures, update, options);
656
+ affected = affected.concat(oldFeatures, updatedFeatures);
657
+ keepFeatures = keepFeatures.concat(updatedFeatures);
658
+ }
659
+ source = keepFeatures;
660
+ }
661
+ return {
662
+ affected,
663
+ source
664
+ };
665
+ }
666
+ /**
667
+ * Gets updated simplified feature(s) based on a diff update object.
668
+ * @param vtFeatures - the original features
669
+ * @param update - the update object to apply
670
+ * @param options - the options to use for the wrap method
671
+ * @returns Updated features. If geometry is updated, returns new feature(s) converted from geojson and wrapped. If only properties are updated, returns feature(s) with tags updated.
672
+ */
673
+ function getUpdatedFeatures(vtFeatures, update, options) {
674
+ const changeGeometry = !!update.newGeometry;
675
+ const changeProps = update.removeAllProperties || update.removeProperties?.length > 0 || update.addOrUpdateProperties?.length > 0;
676
+ if (changeGeometry) {
677
+ const vtFeature = vtFeatures[0];
678
+ let features = convertToInternal({
679
+ type: "FeatureCollection",
680
+ features: [{
681
+ type: "Feature",
682
+ id: vtFeature.id,
683
+ geometry: update.newGeometry,
684
+ properties: changeProps ? applyPropertyUpdates(vtFeature.tags, update) : vtFeature.tags
685
+ }]
686
+ }, options);
687
+ features = wrap(features, options);
688
+ return features;
689
+ }
690
+ if (changeProps) {
691
+ const updated = [];
692
+ for (const vtFeature of vtFeatures) {
693
+ const feature = { ...vtFeature };
694
+ feature.tags = applyPropertyUpdates(feature.tags, update);
695
+ updated.push(feature);
696
+ }
697
+ return updated;
698
+ }
699
+ return vtFeatures;
700
+ }
701
+ /**
702
+ * helper to apply property updates from a diff update object to a properties object
703
+ */
704
+ function applyPropertyUpdates(tags, update) {
705
+ if (update.removeAllProperties) return {};
706
+ const properties = { ...tags || {} };
707
+ if (update.removeProperties) for (const key of update.removeProperties) delete properties[key];
708
+ if (update.addOrUpdateProperties) for (const { key, value } of update.addOrUpdateProperties) properties[key] = value;
709
+ return properties;
710
+ }
711
+ /**
712
+ * Convert a GeoJSON Source Diff to an idempotent hashed representation using Sets and Maps
713
+ */
714
+ function diffToHashed(diff, options) {
715
+ if (!diff) return {
716
+ remove: /* @__PURE__ */ new Set(),
717
+ add: /* @__PURE__ */ new Map(),
718
+ update: /* @__PURE__ */ new Map()
719
+ };
720
+ return {
721
+ removeAll: diff.removeAll,
722
+ remove: new Set(diff.remove || []),
723
+ add: new Map(diff.add?.map((feature) => [options.promoteId ? feature.properties[options.promoteId] : feature.id, feature])),
724
+ update: new Map(diff.update?.map((update) => [update.id, update]))
725
+ };
726
+ }
999
727
 
1000
- return result;
1001
- }
728
+ //#endregion
729
+ //#region node_modules/kdbush/index.js
730
+ const ARRAY_TYPES = [
731
+ Int8Array,
732
+ Uint8Array,
733
+ Uint8ClampedArray,
734
+ Int16Array,
735
+ Uint16Array,
736
+ Int32Array,
737
+ Uint32Array,
738
+ Float32Array,
739
+ Float64Array
740
+ ];
741
+ /** @typedef {Int8ArrayConstructor | Uint8ArrayConstructor | Uint8ClampedArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor} TypedArrayConstructor */
742
+ /** @typedef {Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array} TypedArray */
743
+ const VERSION = 1;
744
+ const HEADER_SIZE = 8;
745
+ const STACK = /* @__PURE__ */ new Uint32Array(96);
746
+ var KDBush = class KDBush {
747
+ /**
748
+ * Creates an index from raw `ArrayBuffer` data.
749
+ * @param {ArrayBufferLike} data
750
+ */
751
+ static from(data) {
752
+ if (!data || data.byteLength === void 0 || data.buffer) throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");
753
+ const [magic, versionAndType] = new Uint8Array(data, 0, 2);
754
+ if (magic !== 219) throw new Error("Data does not appear to be in a KDBush format.");
755
+ const version = versionAndType >> 4;
756
+ if (version !== VERSION) throw new Error(`Got v${version} data when expected v${VERSION}.`);
757
+ const ArrayType = ARRAY_TYPES[versionAndType & 15];
758
+ if (!ArrayType) throw new Error("Unrecognized array type.");
759
+ const [nodeSize] = new Uint16Array(data, 2, 1);
760
+ const [numItems] = new Uint32Array(data, 4, 1);
761
+ return new KDBush(numItems, nodeSize, ArrayType, void 0, data);
762
+ }
763
+ /**
764
+ * Creates an index that will hold a given number of items.
765
+ * @param {number} numItems
766
+ * @param {number} [nodeSize=64] Size of the KD-tree node (64 by default).
767
+ * @param {TypedArrayConstructor} [ArrayType=Float64Array] The array type used for coordinates storage (`Float64Array` by default).
768
+ * @param {ArrayBufferConstructor | SharedArrayBufferConstructor} [ArrayBufferType=ArrayBuffer] The array buffer type used for storage (`ArrayBuffer` by default).
769
+ * @param {ArrayBufferLike} [data] (For internal use only)
770
+ */
771
+ constructor(numItems, nodeSize = 64, ArrayType = Float64Array, ArrayBufferType = ArrayBuffer, data) {
772
+ if (isNaN(numItems) || numItems < 0) throw new Error(`Unexpected numItems value: ${numItems}.`);
773
+ this.numItems = +numItems;
774
+ this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535);
775
+ this.ArrayType = ArrayType;
776
+ this.IndexArrayType = numItems < 65536 ? Uint16Array : Uint32Array;
777
+ const arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType);
778
+ const coordsByteSize = numItems * 2 * this.ArrayType.BYTES_PER_ELEMENT;
779
+ const idsByteSize = numItems * this.IndexArrayType.BYTES_PER_ELEMENT;
780
+ const padCoords = (8 - idsByteSize % 8) % 8;
781
+ if (arrayTypeIndex < 0) throw new Error(`Unexpected typed array class: ${ArrayType}.`);
782
+ if (data) {
783
+ this.data = data;
784
+ this.ids = new this.IndexArrayType(data, HEADER_SIZE, numItems);
785
+ this.coords = new ArrayType(data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);
786
+ this._pos = numItems * 2;
787
+ this._finished = true;
788
+ } else {
789
+ const data = this.data = new ArrayBufferType(HEADER_SIZE + coordsByteSize + idsByteSize + padCoords);
790
+ this.ids = new this.IndexArrayType(data, HEADER_SIZE, numItems);
791
+ this.coords = new ArrayType(data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);
792
+ this._pos = 0;
793
+ this._finished = false;
794
+ new Uint8Array(data, 0, 2).set([219, (VERSION << 4) + arrayTypeIndex]);
795
+ new Uint16Array(data, 2, 1)[0] = nodeSize;
796
+ new Uint32Array(data, 4, 1)[0] = numItems;
797
+ }
798
+ }
799
+ /**
800
+ * Add a point to the index.
801
+ * @param {number} x
802
+ * @param {number} y
803
+ * @returns {number} An incremental index associated with the added item (starting from `0`).
804
+ */
805
+ add(x, y) {
806
+ const index = this._pos >> 1;
807
+ this.ids[index] = index;
808
+ this.coords[this._pos++] = x;
809
+ this.coords[this._pos++] = y;
810
+ return index;
811
+ }
812
+ /**
813
+ * Perform indexing of the added points.
814
+ */
815
+ finish() {
816
+ const numAdded = this._pos >> 1;
817
+ if (numAdded !== this.numItems) throw new Error(`Added ${numAdded} items when expected ${this.numItems}.`);
818
+ sort(this.ids, this.coords, this.nodeSize, 0, this.numItems - 1, 0);
819
+ this._finished = true;
820
+ return this;
821
+ }
822
+ /**
823
+ * Search the index for items within a given bounding box.
824
+ * @param {number} minX
825
+ * @param {number} minY
826
+ * @param {number} maxX
827
+ * @param {number} maxY
828
+ * @returns {number[]} An array of indices correponding to the found items.
829
+ */
830
+ range(minX, minY, maxX, maxY) {
831
+ if (!this._finished) throw new Error("Data not yet indexed - call index.finish().");
832
+ const { ids, coords, nodeSize } = this;
833
+ STACK[0] = 0;
834
+ STACK[1] = ids.length - 1;
835
+ STACK[2] = 0;
836
+ let sp = 3;
837
+ const result = [];
838
+ while (sp > 0) {
839
+ const axis = STACK[--sp];
840
+ const right = STACK[--sp];
841
+ const left = STACK[--sp];
842
+ if (right - left <= nodeSize) {
843
+ for (let i = left; i <= right; i++) {
844
+ const x = coords[2 * i];
845
+ const y = coords[2 * i + 1];
846
+ if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[i]);
847
+ }
848
+ continue;
849
+ }
850
+ const m = left + right >> 1;
851
+ const x = coords[2 * m];
852
+ const y = coords[2 * m + 1];
853
+ if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]);
854
+ if (axis === 0 ? minX <= x : minY <= y) {
855
+ STACK[sp++] = left;
856
+ STACK[sp++] = m - 1;
857
+ STACK[sp++] = 1 - axis;
858
+ }
859
+ if (axis === 0 ? maxX >= x : maxY >= y) {
860
+ STACK[sp++] = m + 1;
861
+ STACK[sp++] = right;
862
+ STACK[sp++] = 1 - axis;
863
+ }
864
+ }
865
+ return result;
866
+ }
867
+ /**
868
+ * Search the index for items within a given radius.
869
+ * @param {number} qx
870
+ * @param {number} qy
871
+ * @param {number} r Query radius.
872
+ * @returns {number[]} An array of indices correponding to the found items.
873
+ */
874
+ within(qx, qy, r) {
875
+ const result = [];
876
+ this.withinInto(qx, qy, r, result);
877
+ return result;
878
+ }
879
+ /**
880
+ * Search the index for items within a given radius, writing matching ids into `out`
881
+ * via indexed assignment (`out[i] = id`). Accepts any indexed-writable container —
882
+ * a typed array sized to the expected upper bound (allocation-free, fast) or a plain
883
+ * `Array` (which will grow as needed). Returns the number of matches written.
884
+ * @param {number} qx
885
+ * @param {number} qy
886
+ * @param {number} r Query radius.
887
+ * @param {number[] | TypedArray} out Container to write matching ids into.
888
+ * @returns {number} The number of matches written to `out`.
889
+ */
890
+ withinInto(qx, qy, r, out) {
891
+ if (!this._finished) throw new Error("Data not yet indexed - call index.finish().");
892
+ const { ids, coords, nodeSize } = this;
893
+ STACK[0] = 0;
894
+ STACK[1] = ids.length - 1;
895
+ STACK[2] = 0;
896
+ let sp = 3;
897
+ let count = 0;
898
+ const r2 = r * r;
899
+ while (sp > 0) {
900
+ const axis = STACK[--sp];
901
+ const right = STACK[--sp];
902
+ const left = STACK[--sp];
903
+ if (right - left <= nodeSize) {
904
+ for (let i = left; i <= right; i++) if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) out[count++] = ids[i];
905
+ continue;
906
+ }
907
+ const m = left + right >> 1;
908
+ const x = coords[2 * m];
909
+ const y = coords[2 * m + 1];
910
+ if (sqDist(x, y, qx, qy) <= r2) out[count++] = ids[m];
911
+ if (axis === 0 ? qx - r <= x : qy - r <= y) {
912
+ STACK[sp++] = left;
913
+ STACK[sp++] = m - 1;
914
+ STACK[sp++] = 1 - axis;
915
+ }
916
+ if (axis === 0 ? qx + r >= x : qy + r >= y) {
917
+ STACK[sp++] = m + 1;
918
+ STACK[sp++] = right;
919
+ STACK[sp++] = 1 - axis;
920
+ }
921
+ }
922
+ return count;
923
+ }
924
+ };
925
+ /**
926
+ * @param {Uint16Array | Uint32Array} ids
927
+ * @param {TypedArray} coords
928
+ * @param {number} nodeSize
929
+ * @param {number} left
930
+ * @param {number} right
931
+ * @param {number} axis
932
+ */
933
+ function sort(ids, coords, nodeSize, left, right, axis) {
934
+ if (right - left <= nodeSize) return;
935
+ const m = left + right >> 1;
936
+ select(ids, coords, m, left, right, axis);
937
+ sort(ids, coords, nodeSize, left, m - 1, 1 - axis);
938
+ sort(ids, coords, nodeSize, m + 1, right, 1 - axis);
939
+ }
940
+ /**
941
+ * Custom Floyd-Rivest selection algorithm: sort ids and coords so that
942
+ * [left..k-1] items are smaller than k-th item (on either x or y axis)
943
+ * @param {Uint16Array | Uint32Array} ids
944
+ * @param {TypedArray} coords
945
+ * @param {number} k
946
+ * @param {number} left
947
+ * @param {number} right
948
+ * @param {number} axis
949
+ */
950
+ function select(ids, coords, k, left, right, axis) {
951
+ while (right > left) {
952
+ if (right - left > 600) {
953
+ const n = right - left + 1;
954
+ const m = k - left + 1;
955
+ const z = Math.log(n);
956
+ const s = .5 * Math.exp(2 * z / 3);
957
+ const sd = .5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
958
+ select(ids, coords, k, Math.max(left, Math.floor(k - m * s / n + sd)), Math.min(right, Math.floor(k + (n - m) * s / n + sd)), axis);
959
+ }
960
+ const t = coords[2 * k + axis];
961
+ let i = left;
962
+ let j = right;
963
+ swapItem(ids, coords, left, k);
964
+ if (coords[2 * right + axis] > t) swapItem(ids, coords, left, right);
965
+ while (i < j) {
966
+ swapItem(ids, coords, i, j);
967
+ i++;
968
+ j--;
969
+ while (coords[2 * i + axis] < t) i++;
970
+ while (coords[2 * j + axis] > t) j--;
971
+ }
972
+ if (coords[2 * left + axis] === t) swapItem(ids, coords, left, j);
973
+ else {
974
+ j++;
975
+ swapItem(ids, coords, j, right);
976
+ }
977
+ if (j <= k) left = j + 1;
978
+ if (k <= j) right = j - 1;
979
+ }
980
+ }
981
+ /**
982
+ * @param {Uint16Array | Uint32Array} ids
983
+ * @param {TypedArray} coords
984
+ * @param {number} i
985
+ * @param {number} j
986
+ */
987
+ function swapItem(ids, coords, i, j) {
988
+ swap(ids, i, j);
989
+ swap(coords, 2 * i, 2 * j);
990
+ swap(coords, 2 * i + 1, 2 * j + 1);
991
+ }
992
+ /**
993
+ * @param {TypedArray} arr
994
+ * @param {number} i
995
+ * @param {number} j
996
+ */
997
+ function swap(arr, i, j) {
998
+ const tmp = arr[i];
999
+ arr[i] = arr[j];
1000
+ arr[j] = tmp;
1001
+ }
1002
+ /**
1003
+ * @param {number} ax
1004
+ * @param {number} ay
1005
+ * @param {number} bx
1006
+ * @param {number} by
1007
+ */
1008
+ function sqDist(ax, ay, bx, by) {
1009
+ const dx = ax - bx;
1010
+ const dy = ay - by;
1011
+ return dx * dx + dy * dy;
1012
+ }
1002
1013
 
1003
- /**
1004
- * Search the index for items within a given radius.
1005
- * @param {number} qx
1006
- * @param {number} qy
1007
- * @param {number} r Query radius.
1008
- * @returns {number[]} An array of indices correponding to the found items.
1009
- */
1010
- within(qx, qy, r) {
1011
- if (!this._finished) throw new Error('Data not yet indexed - call index.finish().');
1014
+ //#endregion
1015
+ //#region src/cluster-tile-index.ts
1016
+ const defaultClusterOptions = {
1017
+ minZoom: 0,
1018
+ maxZoom: 16,
1019
+ minPoints: 2,
1020
+ radius: 40,
1021
+ extent: 512,
1022
+ nodeSize: 64,
1023
+ log: false,
1024
+ generateId: false,
1025
+ reduce: null,
1026
+ map: (props) => props
1027
+ };
1028
+ const OFFSET_ZOOM = 2;
1029
+ const OFFSET_ID = 3;
1030
+ const OFFSET_PARENT = 4;
1031
+ const OFFSET_NUM = 5;
1032
+ const OFFSET_PROP = 6;
1033
+ /**
1034
+ * This class allow clustering of geojson points.
1035
+ */
1036
+ var ClusterTileIndex = class {
1037
+ constructor(options) {
1038
+ this.options = Object.assign(Object.create(defaultClusterOptions), options);
1039
+ this.trees = new Array(this.options.maxZoom + 1);
1040
+ this.stride = this.options.reduce ? 7 : 6;
1041
+ this.clusterProps = [];
1042
+ this.points = [];
1043
+ }
1044
+ /**
1045
+ * Loads GeoJSON point features and builds the internal clustering index.
1046
+ * @param points - GeoJSON point features to cluster.
1047
+ */
1048
+ load(points) {
1049
+ const features = [];
1050
+ for (const point of points) {
1051
+ if (!point.geometry) continue;
1052
+ const [lng, lat] = point.geometry.coordinates;
1053
+ const [x, y] = [projectX(lng), projectY(lat)];
1054
+ const feature = {
1055
+ id: point.id,
1056
+ type: "Point",
1057
+ geometry: [x, y],
1058
+ tags: point.properties
1059
+ };
1060
+ features.push(feature);
1061
+ }
1062
+ this.createIndex(features);
1063
+ }
1064
+ /**
1065
+ * @internal
1066
+ * Loads internal GeoJSONVT point features from a data source and builds the clustering index.
1067
+ * @param features - {@link GeoJSONVTInternalFeature} data source features to filter and cluster.
1068
+ */
1069
+ initialize(features) {
1070
+ const points = [];
1071
+ for (const feature of features) {
1072
+ if (feature.type !== "Point") continue;
1073
+ points.push(feature);
1074
+ }
1075
+ this.createIndex(points);
1076
+ }
1077
+ /**
1078
+ * @internal
1079
+ * Updates the cluster data by rebuilding.
1080
+ * @param features
1081
+ */
1082
+ updateIndex(features, _affected, options) {
1083
+ this.options = Object.assign(Object.create(defaultClusterOptions), options.clusterOptions);
1084
+ this.initialize(features);
1085
+ }
1086
+ createIndex(points) {
1087
+ const { log, minZoom, maxZoom } = this.options;
1088
+ if (log) console.time("total time");
1089
+ const timerId = `prepare ${points.length} points`;
1090
+ if (log) console.time(timerId);
1091
+ this.points = points;
1092
+ const data = [];
1093
+ for (let i = 0; i < points.length; i++) {
1094
+ const p = points[i];
1095
+ if (!p?.geometry) continue;
1096
+ let [x, y] = p.geometry;
1097
+ x = Math.fround(x);
1098
+ y = Math.fround(y);
1099
+ data.push(x, y, Infinity, i, -1, 1);
1100
+ if (this.options.reduce) data.push(0);
1101
+ }
1102
+ let tree = this.trees[maxZoom + 1] = this.createTree(data);
1103
+ if (log) console.timeEnd(timerId);
1104
+ for (let z = maxZoom; z >= minZoom; z--) {
1105
+ const now = Date.now();
1106
+ tree = this.trees[z] = this.createTree(this.cluster(tree, z));
1107
+ if (log) console.log("z%d: %d clusters in %dms", z, tree.numItems, Date.now() - now);
1108
+ }
1109
+ if (log) console.timeEnd("total time");
1110
+ }
1111
+ /**
1112
+ * Returns clusters and/or points within a bounding box at a given zoom level.
1113
+ * @param bbox - Bounding box in `[westLng, southLat, eastLng, northLat]` order.
1114
+ * @param zoom - Zoom level to query.
1115
+ */
1116
+ getClusters(bbox, zoom) {
1117
+ return this.getClustersInternal(bbox, zoom).map((f) => featureToGeoJSON(f));
1118
+ }
1119
+ getClustersInternal(bbox, zoom) {
1120
+ let minLng = ((bbox[0] + 180) % 360 + 360) % 360 - 180;
1121
+ const minLat = Math.max(-90, Math.min(90, bbox[1]));
1122
+ let maxLng = bbox[2] === 180 ? 180 : ((bbox[2] + 180) % 360 + 360) % 360 - 180;
1123
+ const maxLat = Math.max(-90, Math.min(90, bbox[3]));
1124
+ if (bbox[2] - bbox[0] >= 360) {
1125
+ minLng = -180;
1126
+ maxLng = 180;
1127
+ } else if (minLng > maxLng) {
1128
+ const easternHem = this.getClustersInternal([
1129
+ minLng,
1130
+ minLat,
1131
+ 180,
1132
+ maxLat
1133
+ ], zoom);
1134
+ const westernHem = this.getClustersInternal([
1135
+ -180,
1136
+ minLat,
1137
+ maxLng,
1138
+ maxLat
1139
+ ], zoom);
1140
+ return easternHem.concat(westernHem);
1141
+ }
1142
+ const tree = this.trees[this.limitZoom(zoom)];
1143
+ const ids = tree.range(projectX(minLng), projectY(maxLat), projectX(maxLng), projectY(minLat));
1144
+ const data = tree.flatData;
1145
+ const clusters = [];
1146
+ for (const id of ids) {
1147
+ const k = this.stride * id;
1148
+ clusters.push(data[k + OFFSET_NUM] > 1 ? getClusterFeature(data, k, this.clusterProps) : this.points[data[k + OFFSET_ID]]);
1149
+ }
1150
+ return clusters;
1151
+ }
1152
+ /**
1153
+ * Returns the immediate children (clusters or points) of a cluster as GeoJSON.
1154
+ * @param clusterId - The target cluster id.
1155
+ */
1156
+ getChildren(clusterId) {
1157
+ const originId = this.getOriginId(clusterId);
1158
+ const originZoom = this.getOriginZoom(clusterId);
1159
+ const clusterError = /* @__PURE__ */ new Error("No cluster with the specified id: " + clusterId);
1160
+ const tree = this.trees[originZoom];
1161
+ if (!tree) throw clusterError;
1162
+ const data = tree.flatData;
1163
+ if (originId * this.stride >= data.length) throw clusterError;
1164
+ const r = this.options.radius / (this.options.extent * Math.pow(2, originZoom - 1));
1165
+ const x = data[originId * this.stride];
1166
+ const y = data[originId * this.stride + 1];
1167
+ const ids = tree.within(x, y, r);
1168
+ const children = [];
1169
+ for (const id of ids) {
1170
+ const k = id * this.stride;
1171
+ if (data[k + OFFSET_PARENT] === clusterId) children.push(data[k + OFFSET_NUM] > 1 ? getClusterGeoJSON(data, k, this.clusterProps) : featureToGeoJSON(this.points[data[k + OFFSET_ID]]));
1172
+ }
1173
+ if (children.length === 0) throw clusterError;
1174
+ return children;
1175
+ }
1176
+ /**
1177
+ * Returns leaf point features under a cluster, paginated by `limit` and `offset`.
1178
+ * @param clusterId - The target cluster id.
1179
+ * @param limit - Maximum number of points to return (defaults to `10`).
1180
+ * @param offset - Number of points to skip before collecting results (defaults to `0`).
1181
+ */
1182
+ getLeaves(clusterId, limit, offset) {
1183
+ limit = limit || 10;
1184
+ offset = offset || 0;
1185
+ const leaves = [];
1186
+ this.appendLeaves(leaves, clusterId, limit, offset, 0);
1187
+ return leaves;
1188
+ }
1189
+ /**
1190
+ * Generates a vector-tile-like representation of a single tile.
1191
+ * @param z - Tile zoom.
1192
+ * @param x - Tile x coordinate.
1193
+ * @param y - Tile y coordinate.
1194
+ */
1195
+ getTile(z, x, y) {
1196
+ const tree = this.trees[this.limitZoom(z)];
1197
+ if (!tree) return null;
1198
+ const z2 = Math.pow(2, z);
1199
+ const { extent, radius } = this.options;
1200
+ const p = radius / extent;
1201
+ const top = (y - p) / z2;
1202
+ const bottom = (y + 1 + p) / z2;
1203
+ const tile = {
1204
+ transformed: true,
1205
+ features: [],
1206
+ source: null,
1207
+ x,
1208
+ y,
1209
+ z
1210
+ };
1211
+ this.addTileFeatures(tree.range((x - p) / z2, top, (x + 1 + p) / z2, bottom), tree.flatData, x, y, z2, tile);
1212
+ if (x === 0) this.addTileFeatures(tree.range(1 - p / z2, top, 1, bottom), tree.flatData, z2, y, z2, tile);
1213
+ if (x === z2 - 1) this.addTileFeatures(tree.range(0, top, p / z2, bottom), tree.flatData, -1, y, z2, tile);
1214
+ return tile;
1215
+ }
1216
+ /**
1217
+ * Returns the zoom level at which a cluster expands into multiple children.
1218
+ * @param clusterId - The target cluster id.
1219
+ */
1220
+ getClusterExpansionZoom(clusterId) {
1221
+ return this.getOriginZoom(clusterId);
1222
+ }
1223
+ appendLeaves(result, clusterId, limit, offset, skipped) {
1224
+ const children = this.getChildren(clusterId);
1225
+ for (const child of children) {
1226
+ const props = child.properties;
1227
+ if (props?.cluster) if (skipped + props.point_count <= offset) skipped += props.point_count;
1228
+ else skipped = this.appendLeaves(result, props.cluster_id, limit, offset, skipped);
1229
+ else if (skipped < offset) skipped++;
1230
+ else result.push(child);
1231
+ if (result.length === limit) break;
1232
+ }
1233
+ return skipped;
1234
+ }
1235
+ createTree(data) {
1236
+ const tree = new KDBush(data.length / this.stride | 0, this.options.nodeSize, Float32Array);
1237
+ for (let i = 0; i < data.length; i += this.stride) tree.add(data[i], data[i + 1]);
1238
+ tree.finish();
1239
+ tree.flatData = data;
1240
+ tree.data = null;
1241
+ return tree;
1242
+ }
1243
+ addTileFeatures(ids, data, x, y, z2, tile) {
1244
+ for (const i of ids) {
1245
+ const k = i * this.stride;
1246
+ const isCluster = data[k + OFFSET_NUM] > 1;
1247
+ let tags;
1248
+ let px;
1249
+ let py;
1250
+ if (isCluster) {
1251
+ tags = getClusterProperties(data, k, this.clusterProps);
1252
+ px = data[k];
1253
+ py = data[k + 1];
1254
+ } else {
1255
+ const p = this.points[data[k + OFFSET_ID]];
1256
+ tags = p.tags;
1257
+ [px, py] = p.geometry;
1258
+ }
1259
+ const f = {
1260
+ type: 1,
1261
+ geometry: [[Math.round(this.options.extent * (px * z2 - x)), Math.round(this.options.extent * (py * z2 - y))]],
1262
+ tags
1263
+ };
1264
+ let id;
1265
+ if (isCluster || this.options.generateId) id = data[k + OFFSET_ID];
1266
+ else id = this.points[data[k + OFFSET_ID]].id;
1267
+ if (id !== void 0) f.id = id;
1268
+ tile.features.push(f);
1269
+ }
1270
+ }
1271
+ limitZoom(z) {
1272
+ return Math.max(this.options.minZoom, Math.min(Math.floor(+z), this.options.maxZoom + 1));
1273
+ }
1274
+ cluster(tree, zoom) {
1275
+ const { radius, extent, reduce, minPoints } = this.options;
1276
+ const r = radius / (extent * Math.pow(2, zoom));
1277
+ const data = tree.flatData;
1278
+ const nextData = [];
1279
+ const stride = this.stride;
1280
+ for (let i = 0; i < data.length; i += stride) {
1281
+ if (data[i + OFFSET_ZOOM] <= zoom) continue;
1282
+ data[i + OFFSET_ZOOM] = zoom;
1283
+ const x = data[i];
1284
+ const y = data[i + 1];
1285
+ const neighborIds = tree.within(data[i], data[i + 1], r);
1286
+ const numPointsOrigin = data[i + OFFSET_NUM];
1287
+ let numPoints = numPointsOrigin;
1288
+ for (const neighborId of neighborIds) {
1289
+ const k = neighborId * stride;
1290
+ if (data[k + OFFSET_ZOOM] > zoom) numPoints += data[k + OFFSET_NUM];
1291
+ }
1292
+ if (numPoints > numPointsOrigin && numPoints >= minPoints) {
1293
+ let wx = x * numPointsOrigin;
1294
+ let wy = y * numPointsOrigin;
1295
+ let clusterProperties;
1296
+ let clusterPropIndex = -1;
1297
+ const id = ((i / stride | 0) << 5) + (zoom + 1) + this.points.length;
1298
+ for (const neighborId of neighborIds) {
1299
+ const k = neighborId * stride;
1300
+ if (data[k + OFFSET_ZOOM] <= zoom) continue;
1301
+ data[k + OFFSET_ZOOM] = zoom;
1302
+ const numPoints2 = data[k + OFFSET_NUM];
1303
+ wx += data[k] * numPoints2;
1304
+ wy += data[k + 1] * numPoints2;
1305
+ data[k + OFFSET_PARENT] = id;
1306
+ if (reduce) {
1307
+ if (!clusterProperties) {
1308
+ clusterProperties = this.map(data, i, true);
1309
+ clusterPropIndex = this.clusterProps.length;
1310
+ this.clusterProps.push(clusterProperties);
1311
+ }
1312
+ reduce(clusterProperties, this.map(data, k));
1313
+ }
1314
+ }
1315
+ data[i + OFFSET_PARENT] = id;
1316
+ nextData.push(wx / numPoints, wy / numPoints, Infinity, id, -1, numPoints);
1317
+ if (reduce) nextData.push(clusterPropIndex);
1318
+ } else {
1319
+ for (let j = 0; j < stride; j++) nextData.push(data[i + j]);
1320
+ if (numPoints > 1) for (const neighborId of neighborIds) {
1321
+ const k = neighborId * stride;
1322
+ if (data[k + OFFSET_ZOOM] <= zoom) continue;
1323
+ data[k + OFFSET_ZOOM] = zoom;
1324
+ for (let j = 0; j < stride; j++) nextData.push(data[k + j]);
1325
+ }
1326
+ }
1327
+ }
1328
+ return nextData;
1329
+ }
1330
+ getOriginId(clusterId) {
1331
+ return clusterId - this.points.length >> 5;
1332
+ }
1333
+ getOriginZoom(clusterId) {
1334
+ return (clusterId - this.points.length) % 32;
1335
+ }
1336
+ map(data, i, clone) {
1337
+ if (data[i + OFFSET_NUM] > 1) {
1338
+ const props = this.clusterProps[data[i + OFFSET_PROP]];
1339
+ return clone ? Object.assign({}, props) : props;
1340
+ }
1341
+ const original = this.points[data[i + OFFSET_ID]].tags;
1342
+ const result = this.options.map(original);
1343
+ return clone && result === original ? Object.assign({}, result) : result;
1344
+ }
1345
+ };
1346
+ function getClusterFeature(data, i, clusterProps) {
1347
+ return {
1348
+ id: data[i + OFFSET_ID],
1349
+ type: "Point",
1350
+ tags: getClusterProperties(data, i, clusterProps),
1351
+ geometry: [data[i], data[i + 1]]
1352
+ };
1353
+ }
1354
+ function getClusterGeoJSON(data, i, clusterProps) {
1355
+ return {
1356
+ type: "Feature",
1357
+ id: data[i + OFFSET_ID],
1358
+ properties: getClusterProperties(data, i, clusterProps),
1359
+ geometry: {
1360
+ type: "Point",
1361
+ coordinates: [unprojectX(data[i]), unprojectY(data[i + 1])]
1362
+ }
1363
+ };
1364
+ }
1365
+ function getClusterProperties(data, i, clusterProps) {
1366
+ const count = data[i + OFFSET_NUM];
1367
+ const abbrev = count >= 1e4 ? `${Math.round(count / 1e3)}k` : count >= 1e3 ? `${Math.round(count / 100) / 10}k` : count;
1368
+ const propIndex = data[i + OFFSET_PROP];
1369
+ const properties = propIndex === -1 ? {} : Object.assign({}, clusterProps[propIndex]);
1370
+ return Object.assign(properties, {
1371
+ cluster: true,
1372
+ cluster_id: data[i + OFFSET_ID],
1373
+ point_count: count,
1374
+ point_count_abbreviated: abbrev
1375
+ });
1376
+ }
1012
1377
 
1013
- const {ids, coords, nodeSize} = this;
1014
- const stack = [0, ids.length - 1, 0];
1015
- const result = [];
1016
- const r2 = r * r;
1017
-
1018
- // recursively search for items within radius in the kd-sorted arrays
1019
- while (stack.length) {
1020
- const axis = stack.pop() || 0;
1021
- const right = stack.pop() || 0;
1022
- const left = stack.pop() || 0;
1023
-
1024
- // if we reached "tree node", search linearly
1025
- if (right - left <= nodeSize) {
1026
- for (let i = left; i <= right; i++) {
1027
- if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) result.push(ids[i]);
1028
- }
1029
- continue;
1030
- }
1031
-
1032
- // otherwise find the middle index
1033
- const m = (left + right) >> 1;
1034
-
1035
- // include the middle item if it's in range
1036
- const x = coords[2 * m];
1037
- const y = coords[2 * m + 1];
1038
- if (sqDist(x, y, qx, qy) <= r2) result.push(ids[m]);
1039
-
1040
- // queue search in halves that intersect the query
1041
- if (axis === 0 ? qx - r <= x : qy - r <= y) {
1042
- stack.push(left);
1043
- stack.push(m - 1);
1044
- stack.push(1 - axis);
1045
- }
1046
- if (axis === 0 ? qx + r >= x : qy + r >= y) {
1047
- stack.push(m + 1);
1048
- stack.push(right);
1049
- stack.push(1 - axis);
1050
- }
1051
- }
1052
-
1053
- return result;
1054
- }
1055
- }
1378
+ //#endregion
1379
+ //#region src/tile.ts
1380
+ const GEOJSONVT_CLIP_START = "geojsonvt_clip_start";
1381
+ const GEOJSONVT_CLIP_END = "geojsonvt_clip_end";
1382
+ /**
1383
+ * Creates a tile object from the given features
1384
+ * @param features - the features to include in the tile
1385
+ * @param z
1386
+ * @param tx
1387
+ * @param ty
1388
+ * @param options - the options object
1389
+ * @returns the created tile
1390
+ */
1391
+ function createTile(features, z, tx, ty, options) {
1392
+ const tolerance = z === options.maxZoom ? 0 : options.tolerance / ((1 << z) * options.extent);
1393
+ const tile = {
1394
+ transformed: false,
1395
+ features: [],
1396
+ source: null,
1397
+ x: tx,
1398
+ y: ty,
1399
+ z,
1400
+ minX: 2,
1401
+ minY: 1,
1402
+ maxX: -1,
1403
+ maxY: 0,
1404
+ numPoints: 0,
1405
+ numSimplified: 0,
1406
+ numFeatures: features.length
1407
+ };
1408
+ for (const feature of features) addFeature(tile, feature, tolerance, options);
1409
+ return tile;
1410
+ }
1411
+ function addFeature(tile, feature, tolerance, options) {
1412
+ tile.minX = Math.min(tile.minX, feature.minX);
1413
+ tile.minY = Math.min(tile.minY, feature.minY);
1414
+ tile.maxX = Math.max(tile.maxX, feature.maxX);
1415
+ tile.maxY = Math.max(tile.maxY, feature.maxY);
1416
+ switch (feature.type) {
1417
+ case "Point":
1418
+ case "MultiPoint":
1419
+ addPointsTileFeature(tile, feature);
1420
+ return;
1421
+ case "LineString":
1422
+ addLineTileFeautre(tile, feature, tolerance, options);
1423
+ return;
1424
+ case "MultiLineString":
1425
+ case "Polygon":
1426
+ addLinesTileFeature(tile, feature, tolerance);
1427
+ return;
1428
+ case "MultiPolygon":
1429
+ addMultiPolygonTileFeature(tile, feature, tolerance);
1430
+ return;
1431
+ }
1432
+ }
1433
+ function addPointsTileFeature(tile, feature) {
1434
+ const geometry = [];
1435
+ for (let i = 0; i < feature.geometry.length; i += 3) {
1436
+ geometry.push(feature.geometry[i], feature.geometry[i + 1]);
1437
+ tile.numPoints++;
1438
+ tile.numSimplified++;
1439
+ }
1440
+ if (!geometry.length) return;
1441
+ const tileFeature = {
1442
+ type: 1,
1443
+ tags: feature.tags || null,
1444
+ geometry
1445
+ };
1446
+ if (feature.id !== null) tileFeature.id = feature.id;
1447
+ tile.features.push(tileFeature);
1448
+ }
1449
+ function addLineTileFeautre(tile, feature, tolerance, options) {
1450
+ const geometry = [];
1451
+ addLine(geometry, feature.geometry, tile, tolerance, false, false);
1452
+ if (!geometry.length) return;
1453
+ let tags = feature.tags || null;
1454
+ if (options.lineMetrics) {
1455
+ tags = {};
1456
+ for (const key in feature.tags) tags[key] = feature.tags[key];
1457
+ tags[GEOJSONVT_CLIP_START] = feature.geometry.start / feature.geometry.size;
1458
+ tags[GEOJSONVT_CLIP_END] = feature.geometry.end / feature.geometry.size;
1459
+ }
1460
+ const tileFeature = {
1461
+ type: 2,
1462
+ tags,
1463
+ geometry
1464
+ };
1465
+ if (feature.id !== null) tileFeature.id = feature.id;
1466
+ tile.features.push(tileFeature);
1467
+ }
1468
+ function addLinesTileFeature(tile, feature, tolerance) {
1469
+ const geometry = [];
1470
+ for (let i = 0; i < feature.geometry.length; i++) addLine(geometry, feature.geometry[i], tile, tolerance, feature.type === "Polygon", i === 0);
1471
+ if (!geometry.length) return;
1472
+ const tileFeature = {
1473
+ type: feature.type === "Polygon" ? 3 : 2,
1474
+ tags: feature.tags || null,
1475
+ geometry
1476
+ };
1477
+ if (feature.id !== null) tileFeature.id = feature.id;
1478
+ tile.features.push(tileFeature);
1479
+ }
1480
+ function addMultiPolygonTileFeature(tile, feature, tolerance) {
1481
+ const geometry = [];
1482
+ for (let k = 0; k < feature.geometry.length; k++) {
1483
+ const polygon = feature.geometry[k];
1484
+ for (let i = 0; i < polygon.length; i++) addLine(geometry, polygon[i], tile, tolerance, true, i === 0);
1485
+ }
1486
+ if (!geometry.length) return;
1487
+ const tileFeature = {
1488
+ type: 3,
1489
+ tags: feature.tags || null,
1490
+ geometry
1491
+ };
1492
+ if (feature.id !== null) tileFeature.id = feature.id;
1493
+ tile.features.push(tileFeature);
1494
+ }
1495
+ function addLine(result, geom, tile, tolerance, isPolygon, isOuter) {
1496
+ const sqTolerance = tolerance * tolerance;
1497
+ if (tolerance > 0 && geom.size < (isPolygon ? sqTolerance : tolerance)) {
1498
+ tile.numPoints += geom.points.length / 3;
1499
+ return;
1500
+ }
1501
+ const ring = [];
1502
+ for (let i = 0; i < geom.points.length; i += 3) {
1503
+ if (tolerance === 0 || geom.points[i + 2] > sqTolerance) {
1504
+ tile.numSimplified++;
1505
+ ring.push(geom.points[i], geom.points[i + 1]);
1506
+ }
1507
+ tile.numPoints++;
1508
+ }
1509
+ if (isPolygon) rewind(ring, isOuter);
1510
+ result.push(ring);
1511
+ }
1512
+ function rewind(ring, clockwise) {
1513
+ let area = 0;
1514
+ for (let i = 0, len = ring.length, j = len - 2; i < len; j = i, i += 2) area += (ring[i] - ring[j]) * (ring[i + 1] + ring[j + 1]);
1515
+ if (area > 0 !== clockwise) return;
1516
+ for (let i = 0, len = ring.length; i < len / 2; i += 2) {
1517
+ const x = ring[i];
1518
+ const y = ring[i + 1];
1519
+ ring[i] = ring[len - 2 - i];
1520
+ ring[i + 1] = ring[len - 1 - i];
1521
+ ring[len - 2 - i] = x;
1522
+ ring[len - 1 - i] = y;
1523
+ }
1524
+ }
1056
1525
 
1526
+ //#endregion
1527
+ //#region src/transform.ts
1057
1528
  /**
1058
- * @param {Uint16Array | Uint32Array} ids
1059
- * @param {InstanceType<TypedArrayConstructor>} coords
1060
- * @param {number} nodeSize
1061
- * @param {number} left
1062
- * @param {number} right
1063
- * @param {number} axis
1064
- */
1065
- function sort(ids, coords, nodeSize, left, right, axis) {
1066
- if (right - left <= nodeSize) return;
1067
-
1068
- const m = (left + right) >> 1; // middle index
1529
+ * Transforms the coordinates of each feature in the given tile from
1530
+ * mercator-projected space into (extent x extent) tile space.
1531
+ * @param tile - the tile to transform, this gets modified in place
1532
+ * @param extent - the tile extent (usually 4096)
1533
+ * @returns the transformed tile
1534
+ */
1535
+ function transformTile(tile, extent) {
1536
+ if (tile.transformed) return tile;
1537
+ const z2 = 1 << tile.z;
1538
+ const tx = tile.x;
1539
+ const ty = tile.y;
1540
+ for (const feature of tile.features) if (feature.type === 1) transformPointFeature(feature, extent, z2, tx, ty);
1541
+ else transformNonPointFeature(feature, extent, z2, tx, ty);
1542
+ tile.transformed = true;
1543
+ return tile;
1544
+ }
1545
+ /**
1546
+ * Transforms a single point feature from mercator-projected space into (extent x extent) tile space.
1547
+ */
1548
+ function transformPointFeature(feature, extent, z2, tx, ty) {
1549
+ const transformed = feature;
1550
+ const geometry = feature.geometry;
1551
+ const point = [];
1552
+ for (let i = 0; i < geometry.length; i += 2) point.push(transformPoint(geometry[i], geometry[i + 1], extent, z2, tx, ty));
1553
+ transformed.geometry = point;
1554
+ return transformed;
1555
+ }
1556
+ /**
1557
+ * Transforms a single non-point feature from mercator-projected space into (extent x extent) tile space.
1558
+ */
1559
+ function transformNonPointFeature(feature, extent, z2, tx, ty) {
1560
+ const transformed = feature;
1561
+ const geometry = feature.geometry;
1562
+ const nonPoint = [];
1563
+ for (const geom of geometry) {
1564
+ const ring = [];
1565
+ for (let i = 0; i < geom.length; i += 2) ring.push(transformPoint(geom[i], geom[i + 1], extent, z2, tx, ty));
1566
+ nonPoint.push(ring);
1567
+ }
1568
+ transformed.geometry = nonPoint;
1569
+ return transformed;
1570
+ }
1571
+ function transformPoint(x, y, extent, z2, tx, ty) {
1572
+ return [Math.round(extent * (x * z2 - tx)), Math.round(extent * (y * z2 - ty))];
1573
+ }
1069
1574
 
1070
- // sort ids and coords around the middle index so that the halves lie
1071
- // either left/right or top/bottom correspondingly (taking turns)
1072
- select(ids, coords, m, left, right, axis);
1575
+ //#endregion
1576
+ //#region src/tile-index.ts
1577
+ var TileIndex = class {
1578
+ constructor(options) {
1579
+ this.options = options;
1580
+ this.total = 0;
1581
+ this.stats = {};
1582
+ this.tiles = {};
1583
+ this.tileCoords = [];
1584
+ this.stats = {};
1585
+ this.total = 0;
1586
+ }
1587
+ initialize(features) {
1588
+ this.splitTile(features, 0, 0, 0);
1589
+ if (this.options.debug) {
1590
+ if (features.length) console.log("features: %d, points: %d", this.tiles[0].numFeatures, this.tiles[0].numPoints);
1591
+ console.timeEnd("generate tiles");
1592
+ console.log("tiles generated:", this.total, JSON.stringify(this.stats));
1593
+ }
1594
+ }
1595
+ /** {@inheritdoc} */
1596
+ updateIndex(source, affected, options) {
1597
+ if (options.debug > 1) {
1598
+ console.log("invalidating tiles");
1599
+ console.time("invalidating");
1600
+ }
1601
+ this.invalidateTiles(affected);
1602
+ if (options.debug > 1) console.timeEnd("invalidating");
1603
+ const [z, x, y] = [
1604
+ 0,
1605
+ 0,
1606
+ 0
1607
+ ];
1608
+ const rootTile = createTile(source, z, x, y, options);
1609
+ rootTile.source = source;
1610
+ const id = toID(z, x, y);
1611
+ this.tiles[id] = rootTile;
1612
+ this.tileCoords.push({
1613
+ z,
1614
+ x,
1615
+ y,
1616
+ id
1617
+ });
1618
+ if (options.debug) {
1619
+ const key = `z${z}`;
1620
+ this.stats[key] = (this.stats[key] || 0) + 1;
1621
+ this.total++;
1622
+ }
1623
+ }
1624
+ /** {@inheritdoc} */
1625
+ getClusterExpansionZoom(_clusterId) {
1626
+ return null;
1627
+ }
1628
+ /** {@inheritdoc} */
1629
+ getChildren(_clusterId) {
1630
+ return null;
1631
+ }
1632
+ /** {@inheritdoc} */
1633
+ getLeaves(_clusterId, _limit, _offset) {
1634
+ return null;
1635
+ }
1636
+ /** {@inheritdoc} */
1637
+ getTile(z, x, y) {
1638
+ const { extent, debug } = this.options;
1639
+ const z2 = 1 << z;
1640
+ x = x + z2 & z2 - 1;
1641
+ const id = toID(z, x, y);
1642
+ if (this.tiles[id]) return transformTile(this.tiles[id], extent);
1643
+ if (debug > 1) console.log("drilling down to z%d-%d-%d", z, x, y);
1644
+ let z0 = z;
1645
+ let x0 = x;
1646
+ let y0 = y;
1647
+ let parent;
1648
+ while (!parent && z0 > 0) {
1649
+ z0--;
1650
+ x0 = x0 >> 1;
1651
+ y0 = y0 >> 1;
1652
+ parent = this.tiles[toID(z0, x0, y0)];
1653
+ }
1654
+ if (!parent?.source) return null;
1655
+ if (debug > 1) {
1656
+ console.log("found parent tile z%d-%d-%d", z0, x0, y0);
1657
+ console.time("drilling down");
1658
+ }
1659
+ this.splitTile(parent.source, z0, x0, y0, z, x, y);
1660
+ if (debug > 1) console.timeEnd("drilling down");
1661
+ if (!this.tiles[id]) return null;
1662
+ return transformTile(this.tiles[id], extent);
1663
+ }
1664
+ /**
1665
+ * splits features from a parent tile to sub-tiles.
1666
+ * z, x, and y are the coordinates of the parent tile
1667
+ * cz, cx, and cy are the coordinates of the target tile
1668
+ *
1669
+ * If no target tile is specified, splitting stops when we reach the maximum
1670
+ * zoom or the number of points is low as specified in the options.
1671
+ * @internal
1672
+ * @param features - features to split
1673
+ * @param z - tile zoom level
1674
+ * @param x - tile x coordinate
1675
+ * @param y - tile y coordinate
1676
+ * @param cz - target tile zoom level
1677
+ * @param cx - target tile x coordinate
1678
+ * @param cy - target tile y coordinate
1679
+ */
1680
+ splitTile(features, z, x, y, cz, cx, cy) {
1681
+ const stack = [
1682
+ features,
1683
+ z,
1684
+ x,
1685
+ y
1686
+ ];
1687
+ const options = this.options;
1688
+ const debug = options.debug;
1689
+ while (stack.length) {
1690
+ y = stack.pop();
1691
+ x = stack.pop();
1692
+ z = stack.pop();
1693
+ features = stack.pop();
1694
+ const z2 = 1 << z;
1695
+ const id = toID(z, x, y);
1696
+ let tile = this.tiles[id];
1697
+ if (!tile) {
1698
+ if (debug > 1) console.time("creation");
1699
+ tile = this.tiles[id] = createTile(features, z, x, y, options);
1700
+ this.tileCoords.push({
1701
+ z,
1702
+ x,
1703
+ y,
1704
+ id
1705
+ });
1706
+ if (debug) {
1707
+ if (debug > 1) {
1708
+ console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)", z, x, y, tile.numFeatures, tile.numPoints, tile.numSimplified);
1709
+ console.timeEnd("creation");
1710
+ }
1711
+ const key = `z${z}`;
1712
+ this.stats[key] = (this.stats[key] || 0) + 1;
1713
+ this.total++;
1714
+ }
1715
+ }
1716
+ tile.source = features;
1717
+ if (cz == null) {
1718
+ if (z === options.indexMaxZoom || tile.numPoints <= options.indexMaxPoints) continue;
1719
+ } else if (z === options.maxZoom || z === cz) continue;
1720
+ else if (cz != null) {
1721
+ const zoomSteps = cz - z;
1722
+ if (x !== cx >> zoomSteps || y !== cy >> zoomSteps) continue;
1723
+ }
1724
+ tile.source = null;
1725
+ if (!features.length) continue;
1726
+ if (debug > 1) console.time("clipping");
1727
+ const k1 = .5 * options.buffer / options.extent;
1728
+ const k2 = .5 - k1;
1729
+ const k3 = .5 + k1;
1730
+ const k4 = 1 + k1;
1731
+ let tl = null;
1732
+ let bl = null;
1733
+ let tr = null;
1734
+ let br = null;
1735
+ const left = clip(features, z2, x - k1, x + k3, 0, tile.minX, tile.maxX, options);
1736
+ const right = clip(features, z2, x + k2, x + k4, 0, tile.minX, tile.maxX, options);
1737
+ if (left) {
1738
+ tl = clip(left, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options);
1739
+ bl = clip(left, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options);
1740
+ }
1741
+ if (right) {
1742
+ tr = clip(right, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options);
1743
+ br = clip(right, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options);
1744
+ }
1745
+ if (debug > 1) console.timeEnd("clipping");
1746
+ stack.push(tl || [], z + 1, x * 2, y * 2);
1747
+ stack.push(bl || [], z + 1, x * 2, y * 2 + 1);
1748
+ stack.push(tr || [], z + 1, x * 2 + 1, y * 2);
1749
+ stack.push(br || [], z + 1, x * 2 + 1, y * 2 + 1);
1750
+ }
1751
+ }
1752
+ /**
1753
+ * Invalidates (removes) tiles affected by the provided features
1754
+ * @internal
1755
+ * @param features
1756
+ */
1757
+ invalidateTiles(features) {
1758
+ if (!features.length) return;
1759
+ const options = this.options;
1760
+ const { debug } = options;
1761
+ let minX = Infinity;
1762
+ let maxX = -Infinity;
1763
+ let minY = Infinity;
1764
+ let maxY = -Infinity;
1765
+ for (const feature of features) {
1766
+ minX = Math.min(minX, feature.minX);
1767
+ maxX = Math.max(maxX, feature.maxX);
1768
+ minY = Math.min(minY, feature.minY);
1769
+ maxY = Math.max(maxY, feature.maxY);
1770
+ }
1771
+ const k1 = options.buffer / options.extent;
1772
+ const removedLookup = /* @__PURE__ */ new Set();
1773
+ for (const id in this.tiles) {
1774
+ const tile = this.tiles[id];
1775
+ const z2 = 1 << tile.z;
1776
+ const tileMinX = (tile.x - k1) / z2;
1777
+ const tileMaxX = (tile.x + 1 + k1) / z2;
1778
+ const tileMinY = (tile.y - k1) / z2;
1779
+ const tileMaxY = (tile.y + 1 + k1) / z2;
1780
+ if (maxX < tileMinX || minX >= tileMaxX || maxY < tileMinY || minY >= tileMaxY) continue;
1781
+ let intersects = false;
1782
+ for (const feature of features) if (feature.maxX >= tileMinX && feature.minX < tileMaxX && feature.maxY >= tileMinY && feature.minY < tileMaxY) {
1783
+ intersects = true;
1784
+ break;
1785
+ }
1786
+ if (!intersects) continue;
1787
+ if (debug) {
1788
+ if (debug > 1) console.log("invalidate tile z%d-%d-%d (features: %d, points: %d, simplified: %d)", tile.z, tile.x, tile.y, tile.numFeatures, tile.numPoints, tile.numSimplified);
1789
+ const key = `z${tile.z}`;
1790
+ this.stats[key] = (this.stats[key] || 0) - 1;
1791
+ this.total--;
1792
+ }
1793
+ delete this.tiles[id];
1794
+ removedLookup.add(id);
1795
+ }
1796
+ if (removedLookup.size) this.tileCoords = this.tileCoords.filter((c) => !removedLookup.has(c.id));
1797
+ }
1798
+ };
1799
+ function toID(z, x, y) {
1800
+ return ((1 << z) * y + x) * 32 + z;
1801
+ }
1073
1802
 
1074
- // recursively kd-sort first half and second half on the opposite axis
1075
- sort(ids, coords, nodeSize, left, m - 1, 1 - axis);
1076
- sort(ids, coords, nodeSize, m + 1, right, 1 - axis);
1077
- }
1078
-
1079
- /**
1080
- * Custom Floyd-Rivest selection algorithm: sort ids and coords so that
1081
- * [left..k-1] items are smaller than k-th item (on either x or y axis)
1082
- * @param {Uint16Array | Uint32Array} ids
1083
- * @param {InstanceType<TypedArrayConstructor>} coords
1084
- * @param {number} k
1085
- * @param {number} left
1086
- * @param {number} right
1087
- * @param {number} axis
1088
- */
1089
- function select(ids, coords, k, left, right, axis) {
1090
-
1091
- while (right > left) {
1092
- if (right - left > 600) {
1093
- const n = right - left + 1;
1094
- const m = k - left + 1;
1095
- const z = Math.log(n);
1096
- const s = 0.5 * Math.exp(2 * z / 3);
1097
- const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
1098
- const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
1099
- const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
1100
- select(ids, coords, k, newLeft, newRight, axis);
1101
- }
1102
-
1103
- const t = coords[2 * k + axis];
1104
- let i = left;
1105
- let j = right;
1106
-
1107
- swapItem(ids, coords, left, k);
1108
- if (coords[2 * right + axis] > t) swapItem(ids, coords, left, right);
1109
-
1110
- while (i < j) {
1111
- swapItem(ids, coords, i, j);
1112
- i++;
1113
- j--;
1114
- while (coords[2 * i + axis] < t) i++;
1115
- while (coords[2 * j + axis] > t) j--;
1116
- }
1117
-
1118
- if (coords[2 * left + axis] === t) swapItem(ids, coords, left, j);
1119
- else {
1120
- j++;
1121
- swapItem(ids, coords, j, right);
1122
- }
1123
-
1124
- if (j <= k) left = j + 1;
1125
- if (k <= j) right = j - 1;
1126
- }
1127
- }
1128
-
1129
- /**
1130
- * @param {Uint16Array | Uint32Array} ids
1131
- * @param {InstanceType<TypedArrayConstructor>} coords
1132
- * @param {number} i
1133
- * @param {number} j
1134
- */
1135
- function swapItem(ids, coords, i, j) {
1136
- swap(ids, i, j);
1137
- swap(coords, 2 * i, 2 * j);
1138
- swap(coords, 2 * i + 1, 2 * j + 1);
1139
- }
1803
+ //#endregion
1804
+ //#region src/geojsonvt.ts
1805
+ const defaultOptions = {
1806
+ maxZoom: 14,
1807
+ indexMaxZoom: 5,
1808
+ indexMaxPoints: 1e5,
1809
+ tolerance: 3,
1810
+ extent: 4096,
1811
+ buffer: 64,
1812
+ lineMetrics: false,
1813
+ promoteId: null,
1814
+ generateId: false,
1815
+ updateable: false,
1816
+ cluster: false,
1817
+ clusterOptions: defaultClusterOptions,
1818
+ debug: 0
1819
+ };
1820
+ /**
1821
+ * Main class for creating and managing a vector tile index from GeoJSON data.
1822
+ */
1823
+ var GeoJSONVT = class {
1824
+ constructor(data, options) {
1825
+ options = this.options = Object.assign({}, defaultOptions, options);
1826
+ const debug = options.debug;
1827
+ if (debug) console.time("preprocess data");
1828
+ if (options.maxZoom < 0 || options.maxZoom > 24) throw new Error("maxZoom should be in the 0-24 range");
1829
+ if (options.promoteId && options.generateId) throw new Error("promoteId and generateId cannot be used together.");
1830
+ let features = convertToInternal(data, options);
1831
+ if (debug) {
1832
+ console.timeEnd("preprocess data");
1833
+ console.log("index: maxZoom: %d, maxPoints: %d", options.indexMaxZoom, options.indexMaxPoints);
1834
+ console.time("generate tiles");
1835
+ }
1836
+ features = wrap(features, options);
1837
+ if (options.updateable) this.source = features;
1838
+ this.initializeIndex(features, options);
1839
+ }
1840
+ initializeIndex(features, options) {
1841
+ this.tileIndex = options.cluster ? new ClusterTileIndex(options.clusterOptions) : new TileIndex(options);
1842
+ if (!features.length) return;
1843
+ this.tileIndex.initialize(features);
1844
+ }
1845
+ /**
1846
+ * Given z, x, and y tile coordinates, returns the corresponding tile with geometries in tile coordinates, much like MVT data is stored.
1847
+ * @param z - tile zoom level
1848
+ * @param x - tile x coordinate
1849
+ * @param y - tile y coordinate
1850
+ * @returns the transformed tile or null if not found
1851
+ */
1852
+ getTile(z, x, y) {
1853
+ z = +z;
1854
+ x = +x;
1855
+ y = +y;
1856
+ if (z < 0 || z > 24) return null;
1857
+ return this.tileIndex.getTile(z, x, y);
1858
+ }
1859
+ /**
1860
+ * Updates the source data feature set using a {@link GeoJSONVTSourceDiff}
1861
+ * @param diff - the source diff object
1862
+ */
1863
+ updateData(diff, filter) {
1864
+ const options = this.options;
1865
+ if (!options.updateable) throw new Error("to update tile geojson `updateable` option must be set to true");
1866
+ let { affected, source } = applySourceDiff(this.source, diff, options);
1867
+ if (filter) ({affected, source} = this.filterUpdate(source, affected, filter));
1868
+ if (!affected.length) return;
1869
+ this.source = source;
1870
+ this.tileIndex.updateIndex(source, affected, options);
1871
+ }
1872
+ /**
1873
+ * Filter an update using a predicate function. Returns the affected and updated source features.
1874
+ */
1875
+ filterUpdate(source, affected, predicate) {
1876
+ const removeIds = /* @__PURE__ */ new Set();
1877
+ for (const feature of source) {
1878
+ if (feature.id == void 0) continue;
1879
+ if (predicate(featureToGeoJSON(feature))) continue;
1880
+ affected.push(feature);
1881
+ removeIds.add(feature.id);
1882
+ }
1883
+ source = source.filter((feature) => !removeIds.has(feature.id));
1884
+ return {
1885
+ affected,
1886
+ source
1887
+ };
1888
+ }
1889
+ /**
1890
+ * Returns source data as GeoJSON - only available when `updateable` option is set to true.
1891
+ */
1892
+ getData() {
1893
+ if (!this.options.updateable) throw new Error("to retrieve data the `updateable` option must be set to true");
1894
+ return convertToGeoJSON(this.source);
1895
+ }
1896
+ /**
1897
+ * Update supercluster options and regenerate the index.
1898
+ * @param cluster - whether to enable clustering
1899
+ * @param clusterOptions - {@link SuperclusterOptions}
1900
+ */
1901
+ updateClusterOptions(cluster, clusterOptions) {
1902
+ const wasCluster = this.options.cluster;
1903
+ this.options.cluster = cluster;
1904
+ this.options.clusterOptions = clusterOptions;
1905
+ if (wasCluster == cluster) {
1906
+ this.tileIndex.updateIndex(this.source, [], this.options);
1907
+ return;
1908
+ }
1909
+ this.initializeIndex(this.source, this.options);
1910
+ }
1911
+ /**
1912
+ * Returns the zoom level at which a cluster expands into multiple children.
1913
+ * @param clusterId - The target cluster id.
1914
+ * @returns the expansion zoom or null in case of non-clustered source
1915
+ */
1916
+ getClusterExpansionZoom(clusterId) {
1917
+ return this.tileIndex.getClusterExpansionZoom(clusterId);
1918
+ }
1919
+ /**
1920
+ * Returns the immediate children (clusters or points) of a cluster as GeoJSON.
1921
+ * @param clusterId - The target cluster id.
1922
+ * @returns the immediate children or null in case of non-clustered source
1923
+ */
1924
+ getClusterChildren(clusterId) {
1925
+ return this.tileIndex.getChildren(clusterId);
1926
+ }
1927
+ /**
1928
+ * Returns leaf point features under a cluster, paginated by `limit` and `offset`.
1929
+ * @param clusterId - The target cluster id.
1930
+ * @param limit - Maximum number of points to return (defaults to `10`).
1931
+ * @param offset - Number of points to skip before collecting results (defaults to `0`).
1932
+ * @returns leaf point features under a cluster or null in case of non-clustered source
1933
+ */
1934
+ getClusterLeaves(clusterId, limit, offset) {
1935
+ return this.tileIndex.getLeaves(clusterId, limit, offset);
1936
+ }
1937
+ };
1140
1938
 
1939
+ //#endregion
1940
+ //#region src/geojson-to-tile.ts
1141
1941
  /**
1142
- * @param {InstanceType<TypedArrayConstructor>} arr
1143
- * @param {number} i
1144
- * @param {number} j
1145
- */
1146
- function swap(arr, i, j) {
1147
- const tmp = arr[i];
1148
- arr[i] = arr[j];
1149
- arr[j] = tmp;
1150
- }
1151
-
1152
- /**
1153
- * @param {number} ax
1154
- * @param {number} ay
1155
- * @param {number} bx
1156
- * @param {number} by
1157
- */
1158
- function sqDist(ax, ay, bx, by) {
1159
- const dx = ax - bx;
1160
- const dy = ay - by;
1161
- return dx * dx + dy * dy;
1162
- }
1163
-
1164
- const defaultClusterOptions = {
1165
- minZoom: 0,
1166
- maxZoom: 16,
1167
- minPoints: 2,
1168
- radius: 40,
1169
- extent: 512,
1170
- nodeSize: 64,
1171
- log: false,
1172
- generateId: false,
1173
- reduce: null,
1174
- map: (props) => props
1175
- };
1176
- const OFFSET_ZOOM = 2;
1177
- const OFFSET_ID = 3;
1178
- const OFFSET_PARENT = 4;
1179
- const OFFSET_NUM = 5;
1180
- const OFFSET_PROP = 6;
1181
- /**
1182
- * This class allow clustering of geojson points.
1183
- */
1184
- class ClusterTileIndex {
1185
- constructor(options) {
1186
- this.options = Object.assign(Object.create(defaultClusterOptions), options);
1187
- this.trees = new Array(this.options.maxZoom + 1);
1188
- this.stride = this.options.reduce ? 7 : 6;
1189
- this.clusterProps = [];
1190
- this.points = [];
1191
- }
1192
- /**
1193
- * Loads GeoJSON point features and builds the internal clustering index.
1194
- * @param points - GeoJSON point features to cluster.
1195
- */
1196
- load(points) {
1197
- const features = [];
1198
- // Convert GeoJSON point features to GeoJSONVT internal point features
1199
- for (const point of points) {
1200
- if (!point.geometry) {
1201
- continue;
1202
- }
1203
- const [lng, lat] = point.geometry.coordinates;
1204
- const [x, y] = [projectX(lng), projectY(lat)];
1205
- const feature = {
1206
- id: point.id,
1207
- type: 'Point',
1208
- geometry: [x, y],
1209
- tags: point.properties
1210
- };
1211
- features.push(feature);
1212
- }
1213
- this.createIndex(features);
1214
- }
1215
- /**
1216
- * @internal
1217
- * Loads internal GeoJSONVT point features from a data source and builds the clustering index.
1218
- * @param features - {@link GeoJSONVTInternalFeature} data source features to filter and cluster.
1219
- */
1220
- initialize(features) {
1221
- const points = [];
1222
- for (const feature of features) {
1223
- if (feature.type !== 'Point')
1224
- continue;
1225
- points.push(feature);
1226
- }
1227
- this.createIndex(points);
1228
- }
1229
- /**
1230
- * @internal
1231
- * Updates the cluster data by rebuilding.
1232
- * @param features
1233
- */
1234
- updateIndex(features, _affected, options) {
1235
- this.options = Object.assign(Object.create(defaultClusterOptions), options.clusterOptions);
1236
- this.initialize(features);
1237
- }
1238
- createIndex(points) {
1239
- const { log, minZoom, maxZoom } = this.options;
1240
- if (log)
1241
- console.time('total time');
1242
- const timerId = `prepare ${points.length} points`;
1243
- if (log)
1244
- console.time(timerId);
1245
- this.points = points;
1246
- // generate a cluster object for each point and index input points into a KD-tree
1247
- const data = [];
1248
- for (let i = 0; i < points.length; i++) {
1249
- const p = points[i];
1250
- if (!p?.geometry)
1251
- continue;
1252
- let [x, y] = p.geometry;
1253
- x = Math.fround(x);
1254
- y = Math.fround(y);
1255
- // store internal point/cluster data in flat numeric arrays for performance
1256
- data.push(x, y, // projected point coordinates
1257
- Infinity, // the last zoom the point was processed at
1258
- i, // index of the source feature in the original input array
1259
- -1, // parent cluster id
1260
- 1 // number of points in a cluster
1261
- );
1262
- if (this.options.reduce)
1263
- data.push(0); // noop
1264
- }
1265
- let tree = this.trees[maxZoom + 1] = this.createTree(data);
1266
- if (log)
1267
- console.timeEnd(timerId);
1268
- // cluster points on max zoom, then cluster the results on previous zoom, etc.;
1269
- // results in a cluster hierarchy across zoom levels
1270
- for (let z = maxZoom; z >= minZoom; z--) {
1271
- const now = Date.now();
1272
- // create a new set of clusters for the zoom and index them with a KD-tree
1273
- tree = this.trees[z] = this.createTree(this.cluster(tree, z));
1274
- if (log)
1275
- console.log('z%d: %d clusters in %dms', z, tree.numItems, Date.now() - now);
1276
- }
1277
- if (log)
1278
- console.timeEnd('total time');
1279
- }
1280
- /**
1281
- * Returns clusters and/or points within a bounding box at a given zoom level.
1282
- * @param bbox - Bounding box in `[westLng, southLat, eastLng, northLat]` order.
1283
- * @param zoom - Zoom level to query.
1284
- */
1285
- getClusters(bbox, zoom) {
1286
- const clusterInternal = this.getClustersInternal(bbox, zoom);
1287
- return clusterInternal.map((f) => featureToGeoJSON(f));
1288
- }
1289
- getClustersInternal(bbox, zoom) {
1290
- let minLng = ((bbox[0] + 180) % 360 + 360) % 360 - 180;
1291
- const minLat = Math.max(-90, Math.min(90, bbox[1]));
1292
- let maxLng = bbox[2] === 180 ? 180 : ((bbox[2] + 180) % 360 + 360) % 360 - 180;
1293
- const maxLat = Math.max(-90, Math.min(90, bbox[3]));
1294
- if (bbox[2] - bbox[0] >= 360) {
1295
- minLng = -180;
1296
- maxLng = 180;
1297
- }
1298
- else if (minLng > maxLng) {
1299
- const easternHem = this.getClustersInternal([minLng, minLat, 180, maxLat], zoom);
1300
- const westernHem = this.getClustersInternal([-180, minLat, maxLng, maxLat], zoom);
1301
- return easternHem.concat(westernHem);
1302
- }
1303
- const tree = this.trees[this.limitZoom(zoom)];
1304
- const ids = tree.range(projectX(minLng), projectY(maxLat), projectX(maxLng), projectY(minLat));
1305
- const data = tree.flatData;
1306
- const clusters = [];
1307
- for (const id of ids) {
1308
- const k = this.stride * id;
1309
- clusters.push(data[k + OFFSET_NUM] > 1 ? getClusterFeature(data, k, this.clusterProps) : this.points[data[k + OFFSET_ID]]);
1310
- }
1311
- return clusters;
1312
- }
1313
- /**
1314
- * Returns the immediate children (clusters or points) of a cluster as GeoJSON.
1315
- * @param clusterId - The target cluster id.
1316
- */
1317
- getChildren(clusterId) {
1318
- const originId = this.getOriginId(clusterId);
1319
- const originZoom = this.getOriginZoom(clusterId);
1320
- const clusterError = new Error('No cluster with the specified id: ' + clusterId);
1321
- const tree = this.trees[originZoom];
1322
- if (!tree)
1323
- throw clusterError;
1324
- const data = tree.flatData;
1325
- if (originId * this.stride >= data.length)
1326
- throw clusterError;
1327
- const r = this.options.radius / (this.options.extent * Math.pow(2, originZoom - 1));
1328
- const x = data[originId * this.stride];
1329
- const y = data[originId * this.stride + 1];
1330
- const ids = tree.within(x, y, r);
1331
- const children = [];
1332
- for (const id of ids) {
1333
- const k = id * this.stride;
1334
- if (data[k + OFFSET_PARENT] === clusterId) {
1335
- children.push(data[k + OFFSET_NUM] > 1 ? getClusterGeoJSON(data, k, this.clusterProps) : featureToGeoJSON(this.points[data[k + OFFSET_ID]]));
1336
- }
1337
- }
1338
- if (children.length === 0)
1339
- throw clusterError;
1340
- return children;
1341
- }
1342
- /**
1343
- * Returns leaf point features under a cluster, paginated by `limit` and `offset`.
1344
- * @param clusterId - The target cluster id.
1345
- * @param limit - Maximum number of points to return (defaults to `10`).
1346
- * @param offset - Number of points to skip before collecting results (defaults to `0`).
1347
- */
1348
- getLeaves(clusterId, limit, offset) {
1349
- limit = limit || 10;
1350
- offset = offset || 0;
1351
- const leaves = [];
1352
- this.appendLeaves(leaves, clusterId, limit, offset, 0);
1353
- return leaves;
1354
- }
1355
- /**
1356
- * Generates a vector-tile-like representation of a single tile.
1357
- * @param z - Tile zoom.
1358
- * @param x - Tile x coordinate.
1359
- * @param y - Tile y coordinate.
1360
- */
1361
- getTile(z, x, y) {
1362
- const tree = this.trees[this.limitZoom(z)];
1363
- if (!tree) {
1364
- return null;
1365
- }
1366
- const z2 = Math.pow(2, z);
1367
- const { extent, radius } = this.options;
1368
- const p = radius / extent;
1369
- const top = (y - p) / z2;
1370
- const bottom = (y + 1 + p) / z2;
1371
- const tile = {
1372
- transformed: true,
1373
- features: [],
1374
- source: null,
1375
- x: x,
1376
- y: y,
1377
- z: z
1378
- };
1379
- this.addTileFeatures(tree.range((x - p) / z2, top, (x + 1 + p) / z2, bottom), tree.flatData, x, y, z2, tile);
1380
- if (x === 0) {
1381
- this.addTileFeatures(tree.range(1 - p / z2, top, 1, bottom), tree.flatData, z2, y, z2, tile);
1382
- }
1383
- if (x === z2 - 1) {
1384
- this.addTileFeatures(tree.range(0, top, p / z2, bottom), tree.flatData, -1, y, z2, tile);
1385
- }
1386
- return tile;
1387
- }
1388
- /**
1389
- * Returns the zoom level at which a cluster expands into multiple children.
1390
- * @param clusterId - The target cluster id.
1391
- */
1392
- getClusterExpansionZoom(clusterId) {
1393
- return this.getOriginZoom(clusterId);
1394
- }
1395
- appendLeaves(result, clusterId, limit, offset, skipped) {
1396
- const children = this.getChildren(clusterId);
1397
- for (const child of children) {
1398
- const props = child.properties;
1399
- if (props?.cluster) {
1400
- if (skipped + props.point_count <= offset) {
1401
- // skip the whole cluster
1402
- skipped += props.point_count;
1403
- }
1404
- else {
1405
- // enter the cluster
1406
- skipped = this.appendLeaves(result, props.cluster_id, limit, offset, skipped);
1407
- // exit the cluster
1408
- }
1409
- }
1410
- else if (skipped < offset) {
1411
- // skip a single point
1412
- skipped++;
1413
- }
1414
- else {
1415
- // add a single point
1416
- result.push(child);
1417
- }
1418
- if (result.length === limit)
1419
- break;
1420
- }
1421
- return skipped;
1422
- }
1423
- createTree(data) {
1424
- const tree = new KDBush(data.length / this.stride | 0, this.options.nodeSize, Float32Array);
1425
- for (let i = 0; i < data.length; i += this.stride)
1426
- tree.add(data[i], data[i + 1]);
1427
- tree.finish();
1428
- tree.flatData = data;
1429
- tree.data = null; // clear original data to free memory as it isn't used later on.
1430
- return tree;
1431
- }
1432
- addTileFeatures(ids, data, x, y, z2, tile) {
1433
- for (const i of ids) {
1434
- const k = i * this.stride;
1435
- const isCluster = data[k + OFFSET_NUM] > 1;
1436
- let tags;
1437
- let px;
1438
- let py;
1439
- if (isCluster) {
1440
- tags = getClusterProperties(data, k, this.clusterProps);
1441
- px = data[k];
1442
- py = data[k + 1];
1443
- }
1444
- else {
1445
- const p = this.points[data[k + OFFSET_ID]];
1446
- tags = p.tags;
1447
- [px, py] = p.geometry;
1448
- }
1449
- const f = {
1450
- type: 1,
1451
- geometry: [[
1452
- Math.round(this.options.extent * (px * z2 - x)),
1453
- Math.round(this.options.extent * (py * z2 - y))
1454
- ]],
1455
- tags
1456
- };
1457
- // assign id
1458
- let id;
1459
- if (isCluster || this.options.generateId) {
1460
- // optionally generate id for points
1461
- id = data[k + OFFSET_ID];
1462
- }
1463
- else {
1464
- // keep id if already assigned
1465
- id = this.points[data[k + OFFSET_ID]].id;
1466
- }
1467
- if (id !== undefined)
1468
- f.id = id;
1469
- tile.features.push(f);
1470
- }
1471
- }
1472
- limitZoom(z) {
1473
- return Math.max(this.options.minZoom, Math.min(Math.floor(+z), this.options.maxZoom + 1));
1474
- }
1475
- cluster(tree, zoom) {
1476
- const { radius, extent, reduce, minPoints } = this.options;
1477
- const r = radius / (extent * Math.pow(2, zoom));
1478
- const data = tree.flatData;
1479
- const nextData = [];
1480
- const stride = this.stride;
1481
- // loop through each point
1482
- for (let i = 0; i < data.length; i += stride) {
1483
- // if we've already visited the point at this zoom level, skip it
1484
- if (data[i + OFFSET_ZOOM] <= zoom)
1485
- continue;
1486
- data[i + OFFSET_ZOOM] = zoom;
1487
- // find all nearby points
1488
- const x = data[i];
1489
- const y = data[i + 1];
1490
- const neighborIds = tree.within(data[i], data[i + 1], r);
1491
- const numPointsOrigin = data[i + OFFSET_NUM];
1492
- let numPoints = numPointsOrigin;
1493
- // count the number of points in a potential cluster
1494
- for (const neighborId of neighborIds) {
1495
- const k = neighborId * stride;
1496
- // filter out neighbors that are already processed
1497
- if (data[k + OFFSET_ZOOM] > zoom)
1498
- numPoints += data[k + OFFSET_NUM];
1499
- }
1500
- // if there were neighbors to merge, and there are enough points to form a cluster
1501
- if (numPoints > numPointsOrigin && numPoints >= minPoints) {
1502
- let wx = x * numPointsOrigin;
1503
- let wy = y * numPointsOrigin;
1504
- let clusterProperties;
1505
- let clusterPropIndex = -1;
1506
- // encode both zoom and point index on which the cluster originated -- offset by total length of features
1507
- const id = ((i / stride | 0) << 5) + (zoom + 1) + this.points.length;
1508
- for (const neighborId of neighborIds) {
1509
- const k = neighborId * stride;
1510
- if (data[k + OFFSET_ZOOM] <= zoom)
1511
- continue;
1512
- data[k + OFFSET_ZOOM] = zoom; // save the zoom (so it doesn't get processed twice)
1513
- const numPoints2 = data[k + OFFSET_NUM];
1514
- wx += data[k] * numPoints2; // accumulate coordinates for calculating weighted center
1515
- wy += data[k + 1] * numPoints2;
1516
- data[k + OFFSET_PARENT] = id;
1517
- if (reduce) {
1518
- if (!clusterProperties) {
1519
- clusterProperties = this.map(data, i, true);
1520
- clusterPropIndex = this.clusterProps.length;
1521
- this.clusterProps.push(clusterProperties);
1522
- }
1523
- reduce(clusterProperties, this.map(data, k));
1524
- }
1525
- }
1526
- data[i + OFFSET_PARENT] = id;
1527
- nextData.push(wx / numPoints, wy / numPoints, Infinity, id, -1, numPoints);
1528
- if (reduce)
1529
- nextData.push(clusterPropIndex);
1530
- }
1531
- else { // left points as unclustered
1532
- for (let j = 0; j < stride; j++)
1533
- nextData.push(data[i + j]);
1534
- if (numPoints > 1) {
1535
- for (const neighborId of neighborIds) {
1536
- const k = neighborId * stride;
1537
- if (data[k + OFFSET_ZOOM] <= zoom)
1538
- continue;
1539
- data[k + OFFSET_ZOOM] = zoom;
1540
- for (let j = 0; j < stride; j++)
1541
- nextData.push(data[k + j]);
1542
- }
1543
- }
1544
- }
1545
- }
1546
- return nextData;
1547
- }
1548
- // get index of the point from which the cluster originated
1549
- getOriginId(clusterId) {
1550
- return (clusterId - this.points.length) >> 5;
1551
- }
1552
- // get zoom of the point from which the cluster originated
1553
- getOriginZoom(clusterId) {
1554
- return (clusterId - this.points.length) % 32;
1555
- }
1556
- map(data, i, clone) {
1557
- if (data[i + OFFSET_NUM] > 1) {
1558
- const props = this.clusterProps[data[i + OFFSET_PROP]];
1559
- return clone ? Object.assign({}, props) : props;
1560
- }
1561
- const original = this.points[data[i + OFFSET_ID]].tags;
1562
- const result = this.options.map(original);
1563
- return clone && result === original ? Object.assign({}, result) : result;
1564
- }
1565
- }
1566
- function getClusterFeature(data, i, clusterProps) {
1567
- return {
1568
- id: data[i + OFFSET_ID],
1569
- type: 'Point',
1570
- tags: getClusterProperties(data, i, clusterProps),
1571
- geometry: [data[i], data[i + 1]]
1572
- };
1573
- }
1574
- function getClusterGeoJSON(data, i, clusterProps) {
1575
- return {
1576
- type: 'Feature',
1577
- id: data[i + OFFSET_ID],
1578
- properties: getClusterProperties(data, i, clusterProps),
1579
- geometry: {
1580
- type: 'Point',
1581
- coordinates: [unprojectX(data[i]), unprojectY(data[i + 1])]
1582
- }
1583
- };
1584
- }
1585
- function getClusterProperties(data, i, clusterProps) {
1586
- const count = data[i + OFFSET_NUM];
1587
- const abbrev = count >= 10000 ? `${Math.round(count / 1000)}k` :
1588
- count >= 1000 ? `${Math.round(count / 100) / 10}k` : count;
1589
- const propIndex = data[i + OFFSET_PROP];
1590
- const properties = propIndex === -1 ? {} : Object.assign({}, clusterProps[propIndex]);
1591
- return Object.assign(properties, {
1592
- cluster: true,
1593
- cluster_id: data[i + OFFSET_ID],
1594
- point_count: count,
1595
- point_count_abbreviated: abbrev
1596
- });
1597
- }
1598
-
1599
- const GEOJSONVT_CLIP_START = 'geojsonvt_clip_start';
1600
- const GEOJSONVT_CLIP_END = 'geojsonvt_clip_end';
1601
- /**
1602
- * Creates a tile object from the given features
1603
- * @param features - the features to include in the tile
1604
- * @param z
1605
- * @param tx
1606
- * @param ty
1607
- * @param options - the options object
1608
- * @returns the created tile
1609
- */
1610
- function createTile(features, z, tx, ty, options) {
1611
- const tolerance = z === options.maxZoom ? 0 : options.tolerance / ((1 << z) * options.extent);
1612
- const tile = {
1613
- transformed: false,
1614
- features: [],
1615
- source: null,
1616
- x: tx,
1617
- y: ty,
1618
- z: z,
1619
- minX: 2,
1620
- minY: 1,
1621
- maxX: -1,
1622
- maxY: 0,
1623
- numPoints: 0,
1624
- numSimplified: 0,
1625
- numFeatures: features.length
1626
- };
1627
- for (const feature of features) {
1628
- addFeature(tile, feature, tolerance, options);
1629
- }
1630
- return tile;
1631
- }
1632
- function addFeature(tile, feature, tolerance, options) {
1633
- tile.minX = Math.min(tile.minX, feature.minX);
1634
- tile.minY = Math.min(tile.minY, feature.minY);
1635
- tile.maxX = Math.max(tile.maxX, feature.maxX);
1636
- tile.maxY = Math.max(tile.maxY, feature.maxY);
1637
- switch (feature.type) {
1638
- case 'Point':
1639
- case 'MultiPoint':
1640
- addPointsTileFeature(tile, feature);
1641
- return;
1642
- case 'LineString':
1643
- addLineTileFeautre(tile, feature, tolerance, options);
1644
- return;
1645
- case 'MultiLineString':
1646
- case 'Polygon':
1647
- addLinesTileFeature(tile, feature, tolerance);
1648
- return;
1649
- case 'MultiPolygon':
1650
- addMultiPolygonTileFeature(tile, feature, tolerance);
1651
- return;
1652
- }
1653
- }
1654
- function addPointsTileFeature(tile, feature) {
1655
- const geometry = [];
1656
- for (let i = 0; i < feature.geometry.length; i += 3) {
1657
- geometry.push(feature.geometry[i], feature.geometry[i + 1]);
1658
- tile.numPoints++;
1659
- tile.numSimplified++;
1660
- }
1661
- if (!geometry.length)
1662
- return;
1663
- const tileFeature = {
1664
- type: 1,
1665
- tags: feature.tags || null,
1666
- geometry: geometry
1667
- };
1668
- if (feature.id !== null) {
1669
- tileFeature.id = feature.id;
1670
- }
1671
- tile.features.push(tileFeature);
1672
- }
1673
- function addLineTileFeautre(tile, feature, tolerance, options) {
1674
- const geometry = [];
1675
- addLine(geometry, feature.geometry, tile, tolerance, false, false);
1676
- if (!geometry.length)
1677
- return;
1678
- let tags = feature.tags || null;
1679
- if (options.lineMetrics) {
1680
- tags = {};
1681
- for (const key in feature.tags)
1682
- tags[key] = feature.tags[key];
1683
- tags[GEOJSONVT_CLIP_START] = feature.geometry.start / feature.geometry.size;
1684
- tags[GEOJSONVT_CLIP_END] = feature.geometry.end / feature.geometry.size;
1685
- }
1686
- const tileFeature = {
1687
- type: 2,
1688
- tags: tags,
1689
- geometry: geometry
1690
- };
1691
- if (feature.id !== null) {
1692
- tileFeature.id = feature.id;
1693
- }
1694
- tile.features.push(tileFeature);
1695
- }
1696
- function addLinesTileFeature(tile, feature, tolerance) {
1697
- const geometry = [];
1698
- for (let i = 0; i < feature.geometry.length; i++) {
1699
- addLine(geometry, feature.geometry[i], tile, tolerance, feature.type === 'Polygon', i === 0);
1700
- }
1701
- if (!geometry.length)
1702
- return;
1703
- const tileFeature = {
1704
- type: feature.type === 'Polygon' ? 3 : 2,
1705
- tags: feature.tags || null,
1706
- geometry: geometry
1707
- };
1708
- if (feature.id !== null) {
1709
- tileFeature.id = feature.id;
1710
- }
1711
- tile.features.push(tileFeature);
1712
- }
1713
- function addMultiPolygonTileFeature(tile, feature, tolerance) {
1714
- const geometry = [];
1715
- for (let k = 0; k < feature.geometry.length; k++) {
1716
- const polygon = feature.geometry[k];
1717
- for (let i = 0; i < polygon.length; i++) {
1718
- addLine(geometry, polygon[i], tile, tolerance, true, i === 0);
1719
- }
1720
- }
1721
- if (!geometry.length)
1722
- return;
1723
- const tileFeature = {
1724
- type: 3,
1725
- tags: feature.tags || null,
1726
- geometry: geometry
1727
- };
1728
- if (feature.id !== null) {
1729
- tileFeature.id = feature.id;
1730
- }
1731
- tile.features.push(tileFeature);
1732
- }
1733
- function addLine(result, geom, tile, tolerance, isPolygon, isOuter) {
1734
- const sqTolerance = tolerance * tolerance;
1735
- if (tolerance > 0 && (geom.size < (isPolygon ? sqTolerance : tolerance))) {
1736
- tile.numPoints += geom.points.length / 3;
1737
- return;
1738
- }
1739
- const ring = [];
1740
- for (let i = 0; i < geom.points.length; i += 3) {
1741
- if (tolerance === 0 || geom.points[i + 2] > sqTolerance) {
1742
- tile.numSimplified++;
1743
- ring.push(geom.points[i], geom.points[i + 1]);
1744
- }
1745
- tile.numPoints++;
1746
- }
1747
- if (isPolygon)
1748
- rewind(ring, isOuter);
1749
- result.push(ring);
1750
- }
1751
- function rewind(ring, clockwise) {
1752
- let area = 0;
1753
- for (let i = 0, len = ring.length, j = len - 2; i < len; j = i, i += 2) {
1754
- area += (ring[i] - ring[j]) * (ring[i + 1] + ring[j + 1]);
1755
- }
1756
- if (area > 0 !== clockwise)
1757
- return;
1758
- for (let i = 0, len = ring.length; i < len / 2; i += 2) {
1759
- const x = ring[i];
1760
- const y = ring[i + 1];
1761
- ring[i] = ring[len - 2 - i];
1762
- ring[i + 1] = ring[len - 1 - i];
1763
- ring[len - 2 - i] = x;
1764
- ring[len - 1 - i] = y;
1765
- }
1766
- }
1767
-
1768
- /**
1769
- * Transforms the coordinates of each feature in the given tile from
1770
- * mercator-projected space into (extent x extent) tile space.
1771
- * @param tile - the tile to transform, this gets modified in place
1772
- * @param extent - the tile extent (usually 4096)
1773
- * @returns the transformed tile
1774
- */
1775
- function transformTile(tile, extent) {
1776
- if (tile.transformed) {
1777
- return tile;
1778
- }
1779
- const z2 = 1 << tile.z;
1780
- const tx = tile.x;
1781
- const ty = tile.y;
1782
- for (const feature of tile.features) {
1783
- if (feature.type === 1) {
1784
- transformPointFeature(feature, extent, z2, tx, ty);
1785
- }
1786
- else {
1787
- transformNonPointFeature(feature, extent, z2, tx, ty);
1788
- }
1789
- }
1790
- tile.transformed = true;
1791
- return tile;
1792
- }
1793
- /**
1794
- * Transforms a single point feature from mercator-projected space into (extent x extent) tile space.
1795
- */
1796
- function transformPointFeature(feature, extent, z2, tx, ty) {
1797
- const transformed = feature;
1798
- const geometry = feature.geometry;
1799
- const point = [];
1800
- for (let i = 0; i < geometry.length; i += 2) {
1801
- point.push(transformPoint(geometry[i], geometry[i + 1], extent, z2, tx, ty));
1802
- }
1803
- transformed.geometry = point;
1804
- return transformed;
1805
- }
1806
- /**
1807
- * Transforms a single non-point feature from mercator-projected space into (extent x extent) tile space.
1808
- */
1809
- function transformNonPointFeature(feature, extent, z2, tx, ty) {
1810
- const transformed = feature;
1811
- const geometry = feature.geometry;
1812
- const nonPoint = [];
1813
- for (const geom of geometry) {
1814
- const ring = [];
1815
- for (let i = 0; i < geom.length; i += 2) {
1816
- ring.push(transformPoint(geom[i], geom[i + 1], extent, z2, tx, ty));
1817
- }
1818
- nonPoint.push(ring);
1819
- }
1820
- transformed.geometry = nonPoint;
1821
- return transformed;
1822
- }
1823
- function transformPoint(x, y, extent, z2, tx, ty) {
1824
- return [
1825
- Math.round(extent * (x * z2 - tx)),
1826
- Math.round(extent * (y * z2 - ty))
1827
- ];
1828
- }
1829
-
1830
- class TileIndex {
1831
- constructor(options) {
1832
- this.options = options;
1833
- this.total = 0;
1834
- /** @internal */
1835
- this.stats = {};
1836
- this.tiles = {};
1837
- this.tileCoords = [];
1838
- this.stats = {};
1839
- this.total = 0;
1840
- }
1841
- initialize(features) {
1842
- // start slicing from the top tile down
1843
- this.splitTile(features, 0, 0, 0);
1844
- if (this.options.debug) {
1845
- if (features.length)
1846
- console.log('features: %d, points: %d', this.tiles[0].numFeatures, this.tiles[0].numPoints);
1847
- console.timeEnd('generate tiles');
1848
- console.log('tiles generated:', this.total, JSON.stringify(this.stats));
1849
- }
1850
- }
1851
- /** {@inheritdoc} */
1852
- updateIndex(source, affected, options) {
1853
- if (options.debug > 1) {
1854
- console.log('invalidating tiles');
1855
- console.time('invalidating');
1856
- }
1857
- this.invalidateTiles(affected);
1858
- if (options.debug > 1)
1859
- console.timeEnd('invalidating');
1860
- // re-generate root tile with updated feature set
1861
- const [z, x, y] = [0, 0, 0];
1862
- const rootTile = createTile(source, z, x, y, options);
1863
- rootTile.source = source;
1864
- // update tile index with new root tile - ready for getTile calls
1865
- const id = toID(z, x, y);
1866
- this.tiles[id] = rootTile;
1867
- this.tileCoords.push({ z, x, y, id });
1868
- if (options.debug) {
1869
- const key = `z${z}`;
1870
- this.stats[key] = (this.stats[key] || 0) + 1;
1871
- this.total++;
1872
- }
1873
- }
1874
- /** {@inheritdoc} */
1875
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
1876
- getClusterExpansionZoom(_clusterId) {
1877
- return null;
1878
- }
1879
- /** {@inheritdoc} */
1880
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
1881
- getChildren(_clusterId) {
1882
- return null;
1883
- }
1884
- /** {@inheritdoc} */
1885
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
1886
- getLeaves(_clusterId, _limit, _offset) {
1887
- return null;
1888
- }
1889
- /** {@inheritdoc} */
1890
- getTile(z, x, y) {
1891
- const { extent, debug } = this.options;
1892
- const z2 = 1 << z;
1893
- x = (x + z2) & (z2 - 1); // wrap tile x coordinate
1894
- const id = toID(z, x, y);
1895
- if (this.tiles[id]) {
1896
- return transformTile(this.tiles[id], extent);
1897
- }
1898
- if (debug > 1)
1899
- console.log('drilling down to z%d-%d-%d', z, x, y);
1900
- let z0 = z;
1901
- let x0 = x;
1902
- let y0 = y;
1903
- let parent;
1904
- while (!parent && z0 > 0) {
1905
- z0--;
1906
- x0 = x0 >> 1;
1907
- y0 = y0 >> 1;
1908
- parent = this.tiles[toID(z0, x0, y0)];
1909
- }
1910
- if (!parent?.source)
1911
- return null;
1912
- // if we found a parent tile containing the original geometry, we can drill down from it
1913
- if (debug > 1) {
1914
- console.log('found parent tile z%d-%d-%d', z0, x0, y0);
1915
- console.time('drilling down');
1916
- }
1917
- this.splitTile(parent.source, z0, x0, y0, z, x, y);
1918
- if (debug > 1)
1919
- console.timeEnd('drilling down');
1920
- if (!this.tiles[id])
1921
- return null;
1922
- return transformTile(this.tiles[id], extent);
1923
- }
1924
- /**
1925
- * splits features from a parent tile to sub-tiles.
1926
- * z, x, and y are the coordinates of the parent tile
1927
- * cz, cx, and cy are the coordinates of the target tile
1928
- *
1929
- * If no target tile is specified, splitting stops when we reach the maximum
1930
- * zoom or the number of points is low as specified in the options.
1931
- * @internal
1932
- * @param features - features to split
1933
- * @param z - tile zoom level
1934
- * @param x - tile x coordinate
1935
- * @param y - tile y coordinate
1936
- * @param cz - target tile zoom level
1937
- * @param cx - target tile x coordinate
1938
- * @param cy - target tile y coordinate
1939
- */
1940
- splitTile(features, z, x, y, cz, cx, cy) {
1941
- const stack = [features, z, x, y];
1942
- const options = this.options;
1943
- const debug = options.debug;
1944
- // avoid recursion by using a processing queue
1945
- while (stack.length) {
1946
- y = stack.pop();
1947
- x = stack.pop();
1948
- z = stack.pop();
1949
- features = stack.pop();
1950
- const z2 = 1 << z;
1951
- const id = toID(z, x, y);
1952
- let tile = this.tiles[id];
1953
- if (!tile) {
1954
- if (debug > 1)
1955
- console.time('creation');
1956
- tile = this.tiles[id] = createTile(features, z, x, y, options);
1957
- this.tileCoords.push({ z, x, y, id });
1958
- if (debug) {
1959
- if (debug > 1) {
1960
- console.log('tile z%d-%d-%d (features: %d, points: %d, simplified: %d)', z, x, y, tile.numFeatures, tile.numPoints, tile.numSimplified);
1961
- console.timeEnd('creation');
1962
- }
1963
- const key = `z${z}`;
1964
- this.stats[key] = (this.stats[key] || 0) + 1;
1965
- this.total++;
1966
- }
1967
- }
1968
- // save reference to original geometry in tile so that we can drill down later if we stop now
1969
- tile.source = features;
1970
- // if it's the first-pass tiling
1971
- if (cz == null) {
1972
- // stop tiling if we reached max zoom, or if the tile is too simple
1973
- if (z === options.indexMaxZoom || tile.numPoints <= options.indexMaxPoints)
1974
- continue;
1975
- // if a drilldown to a specific tile
1976
- }
1977
- else if (z === options.maxZoom || z === cz) {
1978
- // stop tiling if we reached base zoom or our target tile zoom
1979
- continue;
1980
- }
1981
- else if (cz != null) {
1982
- // stop tiling if it's not an ancestor of the target tile
1983
- const zoomSteps = cz - z;
1984
- if (x !== cx >> zoomSteps || y !== cy >> zoomSteps)
1985
- continue;
1986
- }
1987
- // if we slice further down, no need to keep source geometry
1988
- tile.source = null;
1989
- if (!features.length)
1990
- continue;
1991
- if (debug > 1)
1992
- console.time('clipping');
1993
- // values we'll use for clipping
1994
- const k1 = 0.5 * options.buffer / options.extent;
1995
- const k2 = 0.5 - k1;
1996
- const k3 = 0.5 + k1;
1997
- const k4 = 1 + k1;
1998
- let tl = null;
1999
- let bl = null;
2000
- let tr = null;
2001
- let br = null;
2002
- const left = clip(features, z2, x - k1, x + k3, AxisType.X, tile.minX, tile.maxX, options);
2003
- const right = clip(features, z2, x + k2, x + k4, AxisType.X, tile.minX, tile.maxX, options);
2004
- if (left) {
2005
- tl = clip(left, z2, y - k1, y + k3, AxisType.Y, tile.minY, tile.maxY, options);
2006
- bl = clip(left, z2, y + k2, y + k4, AxisType.Y, tile.minY, tile.maxY, options);
2007
- }
2008
- if (right) {
2009
- tr = clip(right, z2, y - k1, y + k3, AxisType.Y, tile.minY, tile.maxY, options);
2010
- br = clip(right, z2, y + k2, y + k4, AxisType.Y, tile.minY, tile.maxY, options);
2011
- }
2012
- if (debug > 1)
2013
- console.timeEnd('clipping');
2014
- stack.push(tl || [], z + 1, x * 2, y * 2);
2015
- stack.push(bl || [], z + 1, x * 2, y * 2 + 1);
2016
- stack.push(tr || [], z + 1, x * 2 + 1, y * 2);
2017
- stack.push(br || [], z + 1, x * 2 + 1, y * 2 + 1);
2018
- }
2019
- }
2020
- /**
2021
- * Invalidates (removes) tiles affected by the provided features
2022
- * @internal
2023
- * @param features
2024
- */
2025
- invalidateTiles(features) {
2026
- if (!features.length)
2027
- return;
2028
- const options = this.options;
2029
- const { debug } = options;
2030
- // calculate bounding box of all features for trivial reject
2031
- let minX = Infinity;
2032
- let maxX = -Infinity;
2033
- let minY = Infinity;
2034
- let maxY = -Infinity;
2035
- for (const feature of features) {
2036
- minX = Math.min(minX, feature.minX);
2037
- maxX = Math.max(maxX, feature.maxX);
2038
- minY = Math.min(minY, feature.minY);
2039
- maxY = Math.max(maxY, feature.maxY);
2040
- }
2041
- // tile buffer clipping value - not halved as in splitTile above because checking against tile's own extent
2042
- const k1 = options.buffer / options.extent;
2043
- // track removed tile ids for o(1) lookup
2044
- const removedLookup = new Set();
2045
- // iterate through existing tiles and remove ones that are affected by features
2046
- for (const id in this.tiles) {
2047
- const tile = this.tiles[id];
2048
- // calculate tile bounds including buffer
2049
- const z2 = 1 << tile.z;
2050
- const tileMinX = (tile.x - k1) / z2;
2051
- const tileMaxX = (tile.x + 1 + k1) / z2;
2052
- const tileMinY = (tile.y - k1) / z2;
2053
- const tileMaxY = (tile.y + 1 + k1) / z2;
2054
- // trivial reject if feature bounds don't intersect tile
2055
- if (maxX < tileMinX || minX >= tileMaxX ||
2056
- maxY < tileMinY || minY >= tileMaxY) {
2057
- continue;
2058
- }
2059
- // check if any feature intersects with the tile
2060
- let intersects = false;
2061
- for (const feature of features) {
2062
- if (feature.maxX >= tileMinX && feature.minX < tileMaxX &&
2063
- feature.maxY >= tileMinY && feature.minY < tileMaxY) {
2064
- intersects = true;
2065
- break;
2066
- }
2067
- }
2068
- if (!intersects)
2069
- continue;
2070
- if (debug) {
2071
- if (debug > 1) {
2072
- console.log('invalidate tile z%d-%d-%d (features: %d, points: %d, simplified: %d)', tile.z, tile.x, tile.y, tile.numFeatures, tile.numPoints, tile.numSimplified);
2073
- }
2074
- const key = `z${tile.z}`;
2075
- this.stats[key] = (this.stats[key] || 0) - 1;
2076
- this.total--;
2077
- }
2078
- delete this.tiles[id];
2079
- removedLookup.add(id);
2080
- }
2081
- // remove tile coords that are no longer in the index
2082
- if (removedLookup.size) {
2083
- this.tileCoords = this.tileCoords.filter(c => !removedLookup.has(c.id));
2084
- }
2085
- }
2086
- }
2087
- function toID(z, x, y) {
2088
- return (((1 << z) * y + x) * 32) + z;
2089
- }
2090
-
2091
- const defaultOptions = {
2092
- maxZoom: 14,
2093
- indexMaxZoom: 5,
2094
- indexMaxPoints: 100000,
2095
- tolerance: 3,
2096
- extent: 4096,
2097
- buffer: 64,
2098
- lineMetrics: false,
2099
- promoteId: null,
2100
- generateId: false,
2101
- updateable: false,
2102
- cluster: false,
2103
- clusterOptions: defaultClusterOptions,
2104
- debug: 0
2105
- };
2106
- /**
2107
- * Main class for creating and managing a vector tile index from GeoJSON data.
2108
- */
2109
- class GeoJSONVT {
2110
- constructor(data, options) {
2111
- options = this.options = Object.assign({}, defaultOptions, options);
2112
- const debug = options.debug;
2113
- if (debug)
2114
- console.time('preprocess data');
2115
- if (options.maxZoom < 0 || options.maxZoom > 24)
2116
- throw new Error('maxZoom should be in the 0-24 range');
2117
- if (options.promoteId && options.generateId)
2118
- throw new Error('promoteId and generateId cannot be used together.');
2119
- // projects and adds simplification info
2120
- let features = convertToInternal(data, options);
2121
- if (debug) {
2122
- console.timeEnd('preprocess data');
2123
- console.log('index: maxZoom: %d, maxPoints: %d', options.indexMaxZoom, options.indexMaxPoints);
2124
- console.time('generate tiles');
2125
- }
2126
- // wraps features (ie extreme west and extreme east)
2127
- features = wrap(features, options);
2128
- // for updateable indexes, store a copy of the original simplified features
2129
- if (options.updateable) {
2130
- this.source = features;
2131
- }
2132
- this.initializeIndex(features, options);
2133
- }
2134
- initializeIndex(features, options) {
2135
- this.tileIndex = options.cluster ? new ClusterTileIndex(options.clusterOptions) : new TileIndex(options);
2136
- if (!features.length)
2137
- return;
2138
- this.tileIndex.initialize(features);
2139
- }
2140
- /**
2141
- * Given z, x, and y tile coordinates, returns the corresponding tile with geometries in tile coordinates, much like MVT data is stored.
2142
- * @param z - tile zoom level
2143
- * @param x - tile x coordinate
2144
- * @param y - tile y coordinate
2145
- * @returns the transformed tile or null if not found
2146
- */
2147
- getTile(z, x, y) {
2148
- z = +z;
2149
- x = +x;
2150
- y = +y;
2151
- if (z < 0 || z > 24)
2152
- return null;
2153
- return this.tileIndex.getTile(z, x, y);
2154
- }
2155
- /**
2156
- * Updates the source data feature set using a {@link GeoJSONVTSourceDiff}
2157
- * @param diff - the source diff object
2158
- */
2159
- updateData(diff, filter) {
2160
- const options = this.options;
2161
- if (!options.updateable)
2162
- throw new Error('to update tile geojson `updateable` option must be set to true');
2163
- // apply diff and collect affected features and updated source that will be used to invalidate tiles
2164
- let { affected, source } = applySourceDiff(this.source, diff, options);
2165
- if (filter) {
2166
- ({ affected, source } = this.filterUpdate(source, affected, filter));
2167
- }
2168
- // nothing has changed
2169
- if (!affected.length)
2170
- return;
2171
- // update source with new simplified feature set
2172
- this.source = source;
2173
- this.tileIndex.updateIndex(source, affected, options);
2174
- }
2175
- /**
2176
- * Filter an update using a predicate function. Returns the affected and updated source features.
2177
- */
2178
- filterUpdate(source, affected, predicate) {
2179
- const removeIds = new Set();
2180
- for (const feature of source) {
2181
- if (feature.id == undefined)
2182
- continue;
2183
- if (predicate(featureToGeoJSON(feature)))
2184
- continue;
2185
- affected.push(feature);
2186
- removeIds.add(feature.id);
2187
- }
2188
- source = source.filter(feature => !removeIds.has(feature.id));
2189
- return { affected, source };
2190
- }
2191
- /**
2192
- * Returns source data as GeoJSON - only available when `updateable` option is set to true.
2193
- */
2194
- getData() {
2195
- if (!this.options.updateable)
2196
- throw new Error('to retrieve data the `updateable` option must be set to true');
2197
- return convertToGeoJSON(this.source);
2198
- }
2199
- /**
2200
- * Update supercluster options and regenerate the index.
2201
- * @param cluster - whether to enable clustering
2202
- * @param clusterOptions - {@link SuperclusterOptions}
2203
- */
2204
- updateClusterOptions(cluster, clusterOptions) {
2205
- const wasCluster = this.options.cluster;
2206
- this.options.cluster = cluster;
2207
- this.options.clusterOptions = clusterOptions;
2208
- if (wasCluster == cluster) {
2209
- this.tileIndex.updateIndex(this.source, [], this.options);
2210
- return;
2211
- }
2212
- this.initializeIndex(this.source, this.options);
2213
- }
2214
- /**
2215
- * Returns the zoom level at which a cluster expands into multiple children.
2216
- * @param clusterId - The target cluster id.
2217
- * @returns the expansion zoom or null in case of non-clustered source
2218
- */
2219
- getClusterExpansionZoom(clusterId) {
2220
- return this.tileIndex.getClusterExpansionZoom(clusterId);
2221
- }
2222
- /**
2223
- * Returns the immediate children (clusters or points) of a cluster as GeoJSON.
2224
- * @param clusterId - The target cluster id.
2225
- * @returns the immediate children or null in case of non-clustered source
2226
- */
2227
- getClusterChildren(clusterId) {
2228
- return this.tileIndex.getChildren(clusterId);
2229
- }
2230
- /**
2231
- * Returns leaf point features under a cluster, paginated by `limit` and `offset`.
2232
- * @param clusterId - The target cluster id.
2233
- * @param limit - Maximum number of points to return (defaults to `10`).
2234
- * @param offset - Number of points to skip before collecting results (defaults to `0`).
2235
- * @returns leaf point features under a cluster or null in case of non-clustered source
2236
- */
2237
- getClusterLeaves(clusterId, limit, offset) {
2238
- return this.tileIndex.getLeaves(clusterId, limit, offset);
2239
- }
2240
- }
2241
-
2242
- /**
2243
- * Converts GeoJSON data directly to a single vector tile without building a tile index.
2244
- *
2245
- * Unlike the {@link GeoJSONVT} class which builds a hierarchical tile index for efficient
2246
- * repeated tile access, this function generates a single tile on-demand. This is useful when:
2247
- * - You only need one specific tile and don't need to query multiple tiles
2248
- * - The source data is already spatially filtered to the tile's bounding box
2249
- * - You want to avoid the overhead of building a full tile index
2250
- *
2251
- * @example
2252
- * ```ts
2253
- * import {geoJSONToTile} from '@maplibre/geojson-vt';
2254
- *
2255
- * const geojson = {
2256
- * type: 'FeatureCollection',
2257
- * features: [{
2258
- * type: 'Feature',
2259
- * geometry: { type: 'Point', coordinates: [-77.03, 38.90] },
2260
- * properties: { name: 'Washington, D.C.' }
2261
- * }]
2262
- * };
2263
- *
2264
- * const tile = geoJSONToTile(geojson, 10, 292, 391, { extent: 4096 });
2265
- * ```
2266
- *
2267
- * @param data - GeoJSON data (Feature, FeatureCollection, or Geometry)
2268
- * @param z - Tile zoom level
2269
- * @param x - Tile x coordinate
2270
- * @param y - Tile y coordinate
2271
- * @param options - Optional configuration for tile generation
2272
- * @returns The generated tile with geometries in tile coordinates, or null if no features
2273
- */
2274
- function geoJSONToTile(data, z, x, y, options = {}) {
2275
- options = { ...defaultOptions, ...options };
2276
- const { wrap: shouldWrap = false, clip: shouldClip = false } = options;
2277
- let features = convertToInternal(data, options);
2278
- if (shouldWrap) {
2279
- features = wrap(features, options);
2280
- }
2281
- if (shouldClip || options.lineMetrics) {
2282
- const pow2 = 1 << z;
2283
- const buffer = options.buffer / options.extent;
2284
- const left = clip(features, pow2, (x - buffer), (x + 1 + buffer), AxisType.X, -1, 2, options);
2285
- features = clip(left || [], pow2, (y - buffer), (y + 1 + buffer), AxisType.Y, -1, 2, options);
2286
- }
2287
- return transformTile(createTile(features ?? [], z, x, y, options), options.extent);
2288
- }
1942
+ * Converts GeoJSON data directly to a single vector tile without building a tile index.
1943
+ *
1944
+ * Unlike the {@link GeoJSONVT} class which builds a hierarchical tile index for efficient
1945
+ * repeated tile access, this function generates a single tile on-demand. This is useful when:
1946
+ * - You only need one specific tile and don't need to query multiple tiles
1947
+ * - The source data is already spatially filtered to the tile's bounding box
1948
+ * - You want to avoid the overhead of building a full tile index
1949
+ *
1950
+ * @example
1951
+ * ```ts
1952
+ * import {geoJSONToTile} from '@maplibre/geojson-vt';
1953
+ *
1954
+ * const geojson = {
1955
+ * type: 'FeatureCollection',
1956
+ * features: [{
1957
+ * type: 'Feature',
1958
+ * geometry: { type: 'Point', coordinates: [-77.03, 38.90] },
1959
+ * properties: { name: 'Washington, D.C.' }
1960
+ * }]
1961
+ * };
1962
+ *
1963
+ * const tile = geoJSONToTile(geojson, 10, 292, 391, { extent: 4096 });
1964
+ * ```
1965
+ *
1966
+ * @param data - GeoJSON data (Feature, FeatureCollection, or Geometry)
1967
+ * @param z - Tile zoom level
1968
+ * @param x - Tile x coordinate
1969
+ * @param y - Tile y coordinate
1970
+ * @param options - Optional configuration for tile generation
1971
+ * @returns The generated tile with geometries in tile coordinates, or null if no features
1972
+ */
1973
+ function geoJSONToTile(data, z, x, y, options = {}) {
1974
+ options = {
1975
+ ...defaultOptions,
1976
+ ...options
1977
+ };
1978
+ const { wrap: shouldWrap = false, clip: shouldClip = false } = options;
1979
+ let features = convertToInternal(data, options);
1980
+ if (shouldWrap) features = wrap(features, options);
1981
+ if (shouldClip || options.lineMetrics) {
1982
+ const pow2 = 1 << z;
1983
+ const buffer = options.buffer / options.extent;
1984
+ features = clip(clip(features, pow2, x - buffer, x + 1 + buffer, 0, -1, 2, options) || [], pow2, y - buffer, y + 1 + buffer, 1, -1, 2, options);
1985
+ }
1986
+ return transformTile(createTile(features ?? [], z, x, y, options), options.extent);
1987
+ }
2289
1988
 
1989
+ //#endregion
2290
1990
  exports.GEOJSONVT_CLIP_END = GEOJSONVT_CLIP_END;
2291
1991
  exports.GEOJSONVT_CLIP_START = GEOJSONVT_CLIP_START;
2292
1992
  exports.GeoJSONVT = GeoJSONVT;
2293
1993
  exports.Supercluster = ClusterTileIndex;
2294
1994
  exports.geoJSONToTile = geoJSONToTile;
2295
-
2296
- }));
1995
+ });