@maplibre/geojson-vt 6.0.5 → 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,2322 +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
- for (const [id, update] of diff.update) {
741
- const oldFeatures = [];
742
- const keepFeatures = [];
743
- for (const feature of source) {
744
- if (feature.id === id) {
745
- oldFeatures.push(feature);
746
- }
747
- else {
748
- keepFeatures.push(feature);
749
- }
750
- }
751
- if (!oldFeatures.length)
752
- continue;
753
- const updatedFeatures = getUpdatedFeatures(oldFeatures, update, options);
754
- if (!updatedFeatures.length)
755
- continue;
756
- affected.push(...oldFeatures, ...updatedFeatures);
757
- keepFeatures.push(...updatedFeatures);
758
- source = keepFeatures;
759
- }
760
- }
761
- return { affected, source };
762
- }
763
- /**
764
- * Gets updated simplified feature(s) based on a diff update object.
765
- * @param vtFeatures - the original features
766
- * @param update - the update object to apply
767
- * @param options - the options to use for the wrap method
768
- * @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.
769
- */
770
- function getUpdatedFeatures(vtFeatures, update, options) {
771
- const changeGeometry = !!update.newGeometry;
772
- const changeProps = update.removeAllProperties ||
773
- update.removeProperties?.length > 0 ||
774
- update.addOrUpdateProperties?.length > 0;
775
- // if geometry changed, need to create a new geojson feature and convert to internal format
776
- if (changeGeometry) {
777
- const vtFeature = vtFeatures[0];
778
- const geojsonFeature = {
779
- type: 'Feature',
780
- id: vtFeature.id,
781
- geometry: update.newGeometry,
782
- properties: changeProps ? applyPropertyUpdates(vtFeature.tags, update) : vtFeature.tags
783
- };
784
- let features = convertToInternal({ type: 'FeatureCollection', features: [geojsonFeature] }, options);
785
- features = wrap(features, options);
786
- return features;
787
- }
788
- if (changeProps) {
789
- const updated = [];
790
- for (const vtFeature of vtFeatures) {
791
- const feature = { ...vtFeature };
792
- feature.tags = applyPropertyUpdates(feature.tags, update);
793
- updated.push(feature);
794
- }
795
- return updated;
796
- }
797
- return [];
798
- }
799
- /**
800
- * helper to apply property updates from a diff update object to a properties object
801
- */
802
- function applyPropertyUpdates(tags, update) {
803
- if (update.removeAllProperties) {
804
- return {};
805
- }
806
- const properties = { ...tags || {} };
807
- if (update.removeProperties) {
808
- for (const key of update.removeProperties) {
809
- delete properties[key];
810
- }
811
- }
812
- if (update.addOrUpdateProperties) {
813
- for (const { key, value } of update.addOrUpdateProperties) {
814
- properties[key] = value;
815
- }
816
- }
817
- return properties;
818
- }
819
- /**
820
- * Convert a GeoJSON Source Diff to an idempotent hashed representation using Sets and Maps
821
- */
822
- function diffToHashed(diff, options) {
823
- if (!diff)
824
- return {
825
- remove: new Set(),
826
- add: new Map(),
827
- update: new Map()
828
- };
829
- const hashed = {
830
- removeAll: diff.removeAll,
831
- remove: new Set(diff.remove || []),
832
- add: new Map(diff.add?.map(feature => [options.promoteId ? feature.properties[options.promoteId] : feature.id, feature])),
833
- update: new Map(diff.update?.map(update => [update.id, update]))
834
- };
835
- return hashed;
836
- }
837
-
838
- const ARRAY_TYPES = [
839
- Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array,
840
- Int32Array, Uint32Array, Float32Array, Float64Array
841
- ];
842
-
843
- /** @typedef {Int8ArrayConstructor | Uint8ArrayConstructor | Uint8ClampedArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor} TypedArrayConstructor */
844
-
845
- const VERSION = 1; // serialized format version
846
- const HEADER_SIZE = 8;
847
-
848
- class KDBush {
849
-
850
- /**
851
- * Creates an index from raw `ArrayBuffer` data.
852
- * @param {ArrayBuffer} data
853
- */
854
- static from(data) {
855
- if (!(data instanceof ArrayBuffer)) {
856
- throw new Error('Data must be an instance of ArrayBuffer.');
857
- }
858
- const [magic, versionAndType] = new Uint8Array(data, 0, 2);
859
- if (magic !== 0xdb) {
860
- throw new Error('Data does not appear to be in a KDBush format.');
861
- }
862
- const version = versionAndType >> 4;
863
- if (version !== VERSION) {
864
- throw new Error(`Got v${version} data when expected v${VERSION}.`);
865
- }
866
- const ArrayType = ARRAY_TYPES[versionAndType & 0x0f];
867
- if (!ArrayType) {
868
- throw new Error('Unrecognized array type.');
869
- }
870
- const [nodeSize] = new Uint16Array(data, 2, 1);
871
- const [numItems] = new Uint32Array(data, 4, 1);
872
-
873
- return new KDBush(numItems, nodeSize, ArrayType, data);
874
- }
875
-
876
- /**
877
- * Creates an index that will hold a given number of items.
878
- * @param {number} numItems
879
- * @param {number} [nodeSize=64] Size of the KD-tree node (64 by default).
880
- * @param {TypedArrayConstructor} [ArrayType=Float64Array] The array type used for coordinates storage (`Float64Array` by default).
881
- * @param {ArrayBuffer} [data] (For internal use only)
882
- */
883
- constructor(numItems, nodeSize = 64, ArrayType = Float64Array, data) {
884
- if (isNaN(numItems) || numItems < 0) throw new Error(`Unpexpected numItems value: ${numItems}.`);
885
-
886
- this.numItems = +numItems;
887
- this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535);
888
- this.ArrayType = ArrayType;
889
- this.IndexArrayType = numItems < 65536 ? Uint16Array : Uint32Array;
890
-
891
- const arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType);
892
- const coordsByteSize = numItems * 2 * this.ArrayType.BYTES_PER_ELEMENT;
893
- const idsByteSize = numItems * this.IndexArrayType.BYTES_PER_ELEMENT;
894
- const padCoords = (8 - idsByteSize % 8) % 8;
895
-
896
- if (arrayTypeIndex < 0) {
897
- throw new Error(`Unexpected typed array class: ${ArrayType}.`);
898
- }
899
-
900
- if (data && (data instanceof ArrayBuffer)) { // reconstruct an index from a buffer
901
- this.data = data;
902
- this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems);
903
- this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);
904
- this._pos = numItems * 2;
905
- this._finished = true;
906
- } else { // initialize a new index
907
- this.data = new ArrayBuffer(HEADER_SIZE + coordsByteSize + idsByteSize + padCoords);
908
- this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems);
909
- this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);
910
- this._pos = 0;
911
- this._finished = false;
912
-
913
- // set header
914
- new Uint8Array(this.data, 0, 2).set([0xdb, (VERSION << 4) + arrayTypeIndex]);
915
- new Uint16Array(this.data, 2, 1)[0] = nodeSize;
916
- new Uint32Array(this.data, 4, 1)[0] = numItems;
917
- }
918
- }
919
-
920
- /**
921
- * Add a point to the index.
922
- * @param {number} x
923
- * @param {number} y
924
- * @returns {number} An incremental index associated with the added item (starting from `0`).
925
- */
926
- add(x, y) {
927
- const index = this._pos >> 1;
928
- this.ids[index] = index;
929
- this.coords[this._pos++] = x;
930
- this.coords[this._pos++] = y;
931
- return index;
932
- }
933
-
934
- /**
935
- * Perform indexing of the added points.
936
- */
937
- finish() {
938
- const numAdded = this._pos >> 1;
939
- if (numAdded !== this.numItems) {
940
- throw new Error(`Added ${numAdded} items when expected ${this.numItems}.`);
941
- }
942
- // kd-sort both arrays for efficient search
943
- sort(this.ids, this.coords, this.nodeSize, 0, this.numItems - 1, 0);
944
-
945
- this._finished = true;
946
- return this;
947
- }
948
-
949
- /**
950
- * Search the index for items within a given bounding box.
951
- * @param {number} minX
952
- * @param {number} minY
953
- * @param {number} maxX
954
- * @param {number} maxY
955
- * @returns {number[]} An array of indices correponding to the found items.
956
- */
957
- range(minX, minY, maxX, maxY) {
958
- if (!this._finished) throw new Error('Data not yet indexed - call index.finish().');
959
-
960
- const {ids, coords, nodeSize} = this;
961
- const stack = [0, ids.length - 1, 0];
962
- const result = [];
963
-
964
- // recursively search for items in range in the kd-sorted arrays
965
- while (stack.length) {
966
- const axis = stack.pop() || 0;
967
- const right = stack.pop() || 0;
968
- const left = stack.pop() || 0;
969
-
970
- // if we reached "tree node", search linearly
971
- if (right - left <= nodeSize) {
972
- for (let i = left; i <= right; i++) {
973
- const x = coords[2 * i];
974
- const y = coords[2 * i + 1];
975
- if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[i]);
976
- }
977
- continue;
978
- }
979
-
980
- // otherwise find the middle index
981
- const m = (left + right) >> 1;
982
-
983
- // include the middle item if it's in range
984
- const x = coords[2 * m];
985
- const y = coords[2 * m + 1];
986
- if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]);
987
-
988
- // queue search in halves that intersect the query
989
- if (axis === 0 ? minX <= x : minY <= y) {
990
- stack.push(left);
991
- stack.push(m - 1);
992
- stack.push(1 - axis);
993
- }
994
- if (axis === 0 ? maxX >= x : maxY >= y) {
995
- stack.push(m + 1);
996
- stack.push(right);
997
- stack.push(1 - axis);
998
- }
999
- }
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
+ }
1000
727
 
1001
- return result;
1002
- }
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
+ }
1003
1013
 
1004
- /**
1005
- * Search the index for items within a given radius.
1006
- * @param {number} qx
1007
- * @param {number} qy
1008
- * @param {number} r Query radius.
1009
- * @returns {number[]} An array of indices correponding to the found items.
1010
- */
1011
- within(qx, qy, r) {
1012
- 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
+ }
1013
1377
 
1014
- const {ids, coords, nodeSize} = this;
1015
- const stack = [0, ids.length - 1, 0];
1016
- const result = [];
1017
- const r2 = r * r;
1018
-
1019
- // recursively search for items within radius in the kd-sorted arrays
1020
- while (stack.length) {
1021
- const axis = stack.pop() || 0;
1022
- const right = stack.pop() || 0;
1023
- const left = stack.pop() || 0;
1024
-
1025
- // if we reached "tree node", search linearly
1026
- if (right - left <= nodeSize) {
1027
- for (let i = left; i <= right; i++) {
1028
- if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) result.push(ids[i]);
1029
- }
1030
- continue;
1031
- }
1032
-
1033
- // otherwise find the middle index
1034
- const m = (left + right) >> 1;
1035
-
1036
- // include the middle item if it's in range
1037
- const x = coords[2 * m];
1038
- const y = coords[2 * m + 1];
1039
- if (sqDist(x, y, qx, qy) <= r2) result.push(ids[m]);
1040
-
1041
- // queue search in halves that intersect the query
1042
- if (axis === 0 ? qx - r <= x : qy - r <= y) {
1043
- stack.push(left);
1044
- stack.push(m - 1);
1045
- stack.push(1 - axis);
1046
- }
1047
- if (axis === 0 ? qx + r >= x : qy + r >= y) {
1048
- stack.push(m + 1);
1049
- stack.push(right);
1050
- stack.push(1 - axis);
1051
- }
1052
- }
1053
-
1054
- return result;
1055
- }
1056
- }
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
+ }
1057
1525
 
1526
+ //#endregion
1527
+ //#region src/transform.ts
1058
1528
  /**
1059
- * @param {Uint16Array | Uint32Array} ids
1060
- * @param {InstanceType<TypedArrayConstructor>} coords
1061
- * @param {number} nodeSize
1062
- * @param {number} left
1063
- * @param {number} right
1064
- * @param {number} axis
1065
- */
1066
- function sort(ids, coords, nodeSize, left, right, axis) {
1067
- if (right - left <= nodeSize) return;
1068
-
1069
- 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
+ }
1070
1574
 
1071
- // sort ids and coords around the middle index so that the halves lie
1072
- // either left/right or top/bottom correspondingly (taking turns)
1073
- 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
+ }
1074
1802
 
1075
- // recursively kd-sort first half and second half on the opposite axis
1076
- sort(ids, coords, nodeSize, left, m - 1, 1 - axis);
1077
- sort(ids, coords, nodeSize, m + 1, right, 1 - axis);
1078
- }
1079
-
1080
- /**
1081
- * Custom Floyd-Rivest selection algorithm: sort ids and coords so that
1082
- * [left..k-1] items are smaller than k-th item (on either x or y axis)
1083
- * @param {Uint16Array | Uint32Array} ids
1084
- * @param {InstanceType<TypedArrayConstructor>} coords
1085
- * @param {number} k
1086
- * @param {number} left
1087
- * @param {number} right
1088
- * @param {number} axis
1089
- */
1090
- function select(ids, coords, k, left, right, axis) {
1091
-
1092
- while (right > left) {
1093
- if (right - left > 600) {
1094
- const n = right - left + 1;
1095
- const m = k - left + 1;
1096
- const z = Math.log(n);
1097
- const s = 0.5 * Math.exp(2 * z / 3);
1098
- const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
1099
- const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
1100
- const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
1101
- select(ids, coords, k, newLeft, newRight, axis);
1102
- }
1103
-
1104
- const t = coords[2 * k + axis];
1105
- let i = left;
1106
- let j = right;
1107
-
1108
- swapItem(ids, coords, left, k);
1109
- if (coords[2 * right + axis] > t) swapItem(ids, coords, left, right);
1110
-
1111
- while (i < j) {
1112
- swapItem(ids, coords, i, j);
1113
- i++;
1114
- j--;
1115
- while (coords[2 * i + axis] < t) i++;
1116
- while (coords[2 * j + axis] > t) j--;
1117
- }
1118
-
1119
- if (coords[2 * left + axis] === t) swapItem(ids, coords, left, j);
1120
- else {
1121
- j++;
1122
- swapItem(ids, coords, j, right);
1123
- }
1124
-
1125
- if (j <= k) left = j + 1;
1126
- if (k <= j) right = j - 1;
1127
- }
1128
- }
1129
-
1130
- /**
1131
- * @param {Uint16Array | Uint32Array} ids
1132
- * @param {InstanceType<TypedArrayConstructor>} coords
1133
- * @param {number} i
1134
- * @param {number} j
1135
- */
1136
- function swapItem(ids, coords, i, j) {
1137
- swap(ids, i, j);
1138
- swap(coords, 2 * i, 2 * j);
1139
- swap(coords, 2 * i + 1, 2 * j + 1);
1140
- }
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
+ };
1141
1938
 
1939
+ //#endregion
1940
+ //#region src/geojson-to-tile.ts
1142
1941
  /**
1143
- * @param {InstanceType<TypedArrayConstructor>} arr
1144
- * @param {number} i
1145
- * @param {number} j
1146
- */
1147
- function swap(arr, i, j) {
1148
- const tmp = arr[i];
1149
- arr[i] = arr[j];
1150
- arr[j] = tmp;
1151
- }
1152
-
1153
- /**
1154
- * @param {number} ax
1155
- * @param {number} ay
1156
- * @param {number} bx
1157
- * @param {number} by
1158
- */
1159
- function sqDist(ax, ay, bx, by) {
1160
- const dx = ax - bx;
1161
- const dy = ay - by;
1162
- return dx * dx + dy * dy;
1163
- }
1164
-
1165
- const defaultClusterOptions = {
1166
- minZoom: 0,
1167
- maxZoom: 16,
1168
- minPoints: 2,
1169
- radius: 40,
1170
- extent: 512,
1171
- nodeSize: 64,
1172
- log: false,
1173
- generateId: false,
1174
- reduce: null,
1175
- map: (props) => props
1176
- };
1177
- const OFFSET_ZOOM = 2;
1178
- const OFFSET_ID = 3;
1179
- const OFFSET_PARENT = 4;
1180
- const OFFSET_NUM = 5;
1181
- const OFFSET_PROP = 6;
1182
- /**
1183
- * This class allow clustering of geojson points.
1184
- */
1185
- class ClusterTileIndex {
1186
- constructor(options) {
1187
- this.options = Object.assign(Object.create(defaultClusterOptions), options);
1188
- this.trees = new Array(this.options.maxZoom + 1);
1189
- this.stride = this.options.reduce ? 7 : 6;
1190
- this.clusterProps = [];
1191
- this.points = [];
1192
- }
1193
- /**
1194
- * Loads GeoJSON point features and builds the internal clustering index.
1195
- * @param points - GeoJSON point features to cluster.
1196
- */
1197
- load(points) {
1198
- const features = [];
1199
- // Convert GeoJSON point features to GeoJSONVT internal point features
1200
- for (const point of points) {
1201
- if (!point.geometry) {
1202
- continue;
1203
- }
1204
- const [lng, lat] = point.geometry.coordinates;
1205
- const [x, y] = [projectX(lng), projectY(lat)];
1206
- const feature = {
1207
- id: point.id,
1208
- type: 'Point',
1209
- geometry: [x, y],
1210
- tags: point.properties
1211
- };
1212
- features.push(feature);
1213
- }
1214
- this.createIndex(features);
1215
- }
1216
- /**
1217
- * @internal
1218
- * Loads internal GeoJSONVT point features from a data source and builds the clustering index.
1219
- * @param features - {@link GeoJSONVTInternalFeature} data source features to filter and cluster.
1220
- */
1221
- initialize(features) {
1222
- const points = [];
1223
- for (const feature of features) {
1224
- if (feature.type !== 'Point')
1225
- continue;
1226
- points.push(feature);
1227
- }
1228
- this.createIndex(points);
1229
- }
1230
- /**
1231
- * @internal
1232
- * Updates the cluster data by rebuilding.
1233
- * @param features
1234
- */
1235
- updateIndex(features, _affected, options) {
1236
- this.options = Object.assign(Object.create(defaultClusterOptions), options.clusterOptions);
1237
- this.initialize(features);
1238
- }
1239
- createIndex(points) {
1240
- const { log, minZoom, maxZoom } = this.options;
1241
- if (log)
1242
- console.time('total time');
1243
- const timerId = `prepare ${points.length} points`;
1244
- if (log)
1245
- console.time(timerId);
1246
- this.points = points;
1247
- // generate a cluster object for each point and index input points into a KD-tree
1248
- const data = [];
1249
- for (let i = 0; i < points.length; i++) {
1250
- const p = points[i];
1251
- if (!p?.geometry)
1252
- continue;
1253
- let [x, y] = p.geometry;
1254
- x = Math.fround(x);
1255
- y = Math.fround(y);
1256
- // store internal point/cluster data in flat numeric arrays for performance
1257
- data.push(x, y, // projected point coordinates
1258
- Infinity, // the last zoom the point was processed at
1259
- i, // index of the source feature in the original input array
1260
- -1, // parent cluster id
1261
- 1 // number of points in a cluster
1262
- );
1263
- if (this.options.reduce)
1264
- data.push(0); // noop
1265
- }
1266
- let tree = this.trees[maxZoom + 1] = this.createTree(data);
1267
- if (log)
1268
- console.timeEnd(timerId);
1269
- // cluster points on max zoom, then cluster the results on previous zoom, etc.;
1270
- // results in a cluster hierarchy across zoom levels
1271
- for (let z = maxZoom; z >= minZoom; z--) {
1272
- const now = Date.now();
1273
- // create a new set of clusters for the zoom and index them with a KD-tree
1274
- tree = this.trees[z] = this.createTree(this.cluster(tree, z));
1275
- if (log)
1276
- console.log('z%d: %d clusters in %dms', z, tree.numItems, Date.now() - now);
1277
- }
1278
- if (log)
1279
- console.timeEnd('total time');
1280
- }
1281
- /**
1282
- * Returns clusters and/or points within a bounding box at a given zoom level.
1283
- * @param bbox - Bounding box in `[westLng, southLat, eastLng, northLat]` order.
1284
- * @param zoom - Zoom level to query.
1285
- */
1286
- getClusters(bbox, zoom) {
1287
- const clusterInternal = this.getClustersInternal(bbox, zoom);
1288
- return clusterInternal.map((f) => featureToGeoJSON(f));
1289
- }
1290
- getClustersInternal(bbox, zoom) {
1291
- let minLng = ((bbox[0] + 180) % 360 + 360) % 360 - 180;
1292
- const minLat = Math.max(-90, Math.min(90, bbox[1]));
1293
- let maxLng = bbox[2] === 180 ? 180 : ((bbox[2] + 180) % 360 + 360) % 360 - 180;
1294
- const maxLat = Math.max(-90, Math.min(90, bbox[3]));
1295
- if (bbox[2] - bbox[0] >= 360) {
1296
- minLng = -180;
1297
- maxLng = 180;
1298
- }
1299
- else if (minLng > maxLng) {
1300
- const easternHem = this.getClustersInternal([minLng, minLat, 180, maxLat], zoom);
1301
- const westernHem = this.getClustersInternal([-180, minLat, maxLng, maxLat], zoom);
1302
- return easternHem.concat(westernHem);
1303
- }
1304
- const tree = this.trees[this.limitZoom(zoom)];
1305
- const ids = tree.range(projectX(minLng), projectY(maxLat), projectX(maxLng), projectY(minLat));
1306
- const data = tree.flatData;
1307
- const clusters = [];
1308
- for (const id of ids) {
1309
- const k = this.stride * id;
1310
- clusters.push(data[k + OFFSET_NUM] > 1 ? getClusterFeature(data, k, this.clusterProps) : this.points[data[k + OFFSET_ID]]);
1311
- }
1312
- return clusters;
1313
- }
1314
- /**
1315
- * Returns the immediate children (clusters or points) of a cluster as GeoJSON.
1316
- * @param clusterId - The target cluster id.
1317
- */
1318
- getChildren(clusterId) {
1319
- const originId = this.getOriginId(clusterId);
1320
- const originZoom = this.getOriginZoom(clusterId);
1321
- const clusterError = new Error('No cluster with the specified id: ' + clusterId);
1322
- const tree = this.trees[originZoom];
1323
- if (!tree)
1324
- throw clusterError;
1325
- const data = tree.flatData;
1326
- if (originId * this.stride >= data.length)
1327
- throw clusterError;
1328
- const r = this.options.radius / (this.options.extent * Math.pow(2, originZoom - 1));
1329
- const x = data[originId * this.stride];
1330
- const y = data[originId * this.stride + 1];
1331
- const ids = tree.within(x, y, r);
1332
- const children = [];
1333
- for (const id of ids) {
1334
- const k = id * this.stride;
1335
- if (data[k + OFFSET_PARENT] === clusterId) {
1336
- children.push(data[k + OFFSET_NUM] > 1 ? getClusterGeoJSON(data, k, this.clusterProps) : featureToGeoJSON(this.points[data[k + OFFSET_ID]]));
1337
- }
1338
- }
1339
- if (children.length === 0)
1340
- throw clusterError;
1341
- return children;
1342
- }
1343
- /**
1344
- * Returns leaf point features under a cluster, paginated by `limit` and `offset`.
1345
- * @param clusterId - The target cluster id.
1346
- * @param limit - Maximum number of points to return (defaults to `10`).
1347
- * @param offset - Number of points to skip before collecting results (defaults to `0`).
1348
- */
1349
- getLeaves(clusterId, limit, offset) {
1350
- limit = limit || 10;
1351
- offset = offset || 0;
1352
- const leaves = [];
1353
- this.appendLeaves(leaves, clusterId, limit, offset, 0);
1354
- return leaves;
1355
- }
1356
- /**
1357
- * Generates a vector-tile-like representation of a single tile.
1358
- * @param z - Tile zoom.
1359
- * @param x - Tile x coordinate.
1360
- * @param y - Tile y coordinate.
1361
- */
1362
- getTile(z, x, y) {
1363
- const tree = this.trees[this.limitZoom(z)];
1364
- if (!tree) {
1365
- return null;
1366
- }
1367
- const z2 = Math.pow(2, z);
1368
- const { extent, radius } = this.options;
1369
- const p = radius / extent;
1370
- const top = (y - p) / z2;
1371
- const bottom = (y + 1 + p) / z2;
1372
- const tile = {
1373
- transformed: true,
1374
- features: [],
1375
- source: null,
1376
- x: x,
1377
- y: y,
1378
- z: z
1379
- };
1380
- this.addTileFeatures(tree.range((x - p) / z2, top, (x + 1 + p) / z2, bottom), tree.flatData, x, y, z2, tile);
1381
- if (x === 0) {
1382
- this.addTileFeatures(tree.range(1 - p / z2, top, 1, bottom), tree.flatData, z2, y, z2, tile);
1383
- }
1384
- if (x === z2 - 1) {
1385
- this.addTileFeatures(tree.range(0, top, p / z2, bottom), tree.flatData, -1, y, z2, tile);
1386
- }
1387
- return tile;
1388
- }
1389
- /**
1390
- * Returns the zoom level at which a cluster expands into multiple children.
1391
- * @param clusterId - The target cluster id.
1392
- */
1393
- getClusterExpansionZoom(clusterId) {
1394
- return this.getOriginZoom(clusterId);
1395
- }
1396
- appendLeaves(result, clusterId, limit, offset, skipped) {
1397
- const children = this.getChildren(clusterId);
1398
- for (const child of children) {
1399
- const props = child.properties;
1400
- if (props?.cluster) {
1401
- if (skipped + props.point_count <= offset) {
1402
- // skip the whole cluster
1403
- skipped += props.point_count;
1404
- }
1405
- else {
1406
- // enter the cluster
1407
- skipped = this.appendLeaves(result, props.cluster_id, limit, offset, skipped);
1408
- // exit the cluster
1409
- }
1410
- }
1411
- else if (skipped < offset) {
1412
- // skip a single point
1413
- skipped++;
1414
- }
1415
- else {
1416
- // add a single point
1417
- result.push(child);
1418
- }
1419
- if (result.length === limit)
1420
- break;
1421
- }
1422
- return skipped;
1423
- }
1424
- createTree(data) {
1425
- const tree = new KDBush(data.length / this.stride | 0, this.options.nodeSize, Float32Array);
1426
- for (let i = 0; i < data.length; i += this.stride)
1427
- tree.add(data[i], data[i + 1]);
1428
- tree.finish();
1429
- tree.flatData = data;
1430
- tree.data = null; // clear original data to free memory as it isn't used later on.
1431
- return tree;
1432
- }
1433
- addTileFeatures(ids, data, x, y, z2, tile) {
1434
- for (const i of ids) {
1435
- const k = i * this.stride;
1436
- const isCluster = data[k + OFFSET_NUM] > 1;
1437
- let tags;
1438
- let px;
1439
- let py;
1440
- if (isCluster) {
1441
- tags = getClusterProperties(data, k, this.clusterProps);
1442
- px = data[k];
1443
- py = data[k + 1];
1444
- }
1445
- else {
1446
- const p = this.points[data[k + OFFSET_ID]];
1447
- tags = p.tags;
1448
- [px, py] = p.geometry;
1449
- }
1450
- const f = {
1451
- type: 1,
1452
- geometry: [[
1453
- Math.round(this.options.extent * (px * z2 - x)),
1454
- Math.round(this.options.extent * (py * z2 - y))
1455
- ]],
1456
- tags
1457
- };
1458
- // assign id
1459
- let id;
1460
- if (isCluster || this.options.generateId) {
1461
- // optionally generate id for points
1462
- id = data[k + OFFSET_ID];
1463
- }
1464
- else {
1465
- // keep id if already assigned
1466
- id = this.points[data[k + OFFSET_ID]].id;
1467
- }
1468
- if (id !== undefined)
1469
- f.id = id;
1470
- tile.features.push(f);
1471
- }
1472
- }
1473
- limitZoom(z) {
1474
- return Math.max(this.options.minZoom, Math.min(Math.floor(+z), this.options.maxZoom + 1));
1475
- }
1476
- cluster(tree, zoom) {
1477
- const { radius, extent, reduce, minPoints } = this.options;
1478
- const r = radius / (extent * Math.pow(2, zoom));
1479
- const data = tree.flatData;
1480
- const nextData = [];
1481
- const stride = this.stride;
1482
- // loop through each point
1483
- for (let i = 0; i < data.length; i += stride) {
1484
- // if we've already visited the point at this zoom level, skip it
1485
- if (data[i + OFFSET_ZOOM] <= zoom)
1486
- continue;
1487
- data[i + OFFSET_ZOOM] = zoom;
1488
- // find all nearby points
1489
- const x = data[i];
1490
- const y = data[i + 1];
1491
- const neighborIds = tree.within(data[i], data[i + 1], r);
1492
- const numPointsOrigin = data[i + OFFSET_NUM];
1493
- let numPoints = numPointsOrigin;
1494
- // count the number of points in a potential cluster
1495
- for (const neighborId of neighborIds) {
1496
- const k = neighborId * stride;
1497
- // filter out neighbors that are already processed
1498
- if (data[k + OFFSET_ZOOM] > zoom)
1499
- numPoints += data[k + OFFSET_NUM];
1500
- }
1501
- // if there were neighbors to merge, and there are enough points to form a cluster
1502
- if (numPoints > numPointsOrigin && numPoints >= minPoints) {
1503
- let wx = x * numPointsOrigin;
1504
- let wy = y * numPointsOrigin;
1505
- let clusterProperties;
1506
- let clusterPropIndex = -1;
1507
- // encode both zoom and point index on which the cluster originated -- offset by total length of features
1508
- const id = ((i / stride | 0) << 5) + (zoom + 1) + this.points.length;
1509
- for (const neighborId of neighborIds) {
1510
- const k = neighborId * stride;
1511
- if (data[k + OFFSET_ZOOM] <= zoom)
1512
- continue;
1513
- data[k + OFFSET_ZOOM] = zoom; // save the zoom (so it doesn't get processed twice)
1514
- const numPoints2 = data[k + OFFSET_NUM];
1515
- wx += data[k] * numPoints2; // accumulate coordinates for calculating weighted center
1516
- wy += data[k + 1] * numPoints2;
1517
- data[k + OFFSET_PARENT] = id;
1518
- if (reduce) {
1519
- if (!clusterProperties) {
1520
- clusterProperties = this.map(data, i, true);
1521
- clusterPropIndex = this.clusterProps.length;
1522
- this.clusterProps.push(clusterProperties);
1523
- }
1524
- reduce(clusterProperties, this.map(data, k));
1525
- }
1526
- }
1527
- data[i + OFFSET_PARENT] = id;
1528
- nextData.push(wx / numPoints, wy / numPoints, Infinity, id, -1, numPoints);
1529
- if (reduce)
1530
- nextData.push(clusterPropIndex);
1531
- }
1532
- else { // left points as unclustered
1533
- for (let j = 0; j < stride; j++)
1534
- nextData.push(data[i + j]);
1535
- if (numPoints > 1) {
1536
- for (const neighborId of neighborIds) {
1537
- const k = neighborId * stride;
1538
- if (data[k + OFFSET_ZOOM] <= zoom)
1539
- continue;
1540
- data[k + OFFSET_ZOOM] = zoom;
1541
- for (let j = 0; j < stride; j++)
1542
- nextData.push(data[k + j]);
1543
- }
1544
- }
1545
- }
1546
- }
1547
- return nextData;
1548
- }
1549
- // get index of the point from which the cluster originated
1550
- getOriginId(clusterId) {
1551
- return (clusterId - this.points.length) >> 5;
1552
- }
1553
- // get zoom of the point from which the cluster originated
1554
- getOriginZoom(clusterId) {
1555
- return (clusterId - this.points.length) % 32;
1556
- }
1557
- map(data, i, clone) {
1558
- if (data[i + OFFSET_NUM] > 1) {
1559
- const props = this.clusterProps[data[i + OFFSET_PROP]];
1560
- return clone ? Object.assign({}, props) : props;
1561
- }
1562
- const original = this.points[data[i + OFFSET_ID]].tags;
1563
- const result = this.options.map(original);
1564
- return clone && result === original ? Object.assign({}, result) : result;
1565
- }
1566
- }
1567
- function getClusterFeature(data, i, clusterProps) {
1568
- return {
1569
- id: data[i + OFFSET_ID],
1570
- type: 'Point',
1571
- tags: getClusterProperties(data, i, clusterProps),
1572
- geometry: [data[i], data[i + 1]]
1573
- };
1574
- }
1575
- function getClusterGeoJSON(data, i, clusterProps) {
1576
- return {
1577
- type: 'Feature',
1578
- id: data[i + OFFSET_ID],
1579
- properties: getClusterProperties(data, i, clusterProps),
1580
- geometry: {
1581
- type: 'Point',
1582
- coordinates: [unprojectX(data[i]), unprojectY(data[i + 1])]
1583
- }
1584
- };
1585
- }
1586
- function getClusterProperties(data, i, clusterProps) {
1587
- const count = data[i + OFFSET_NUM];
1588
- const abbrev = count >= 10000 ? `${Math.round(count / 1000)}k` :
1589
- count >= 1000 ? `${Math.round(count / 100) / 10}k` : count;
1590
- const propIndex = data[i + OFFSET_PROP];
1591
- const properties = propIndex === -1 ? {} : Object.assign({}, clusterProps[propIndex]);
1592
- return Object.assign(properties, {
1593
- cluster: true,
1594
- cluster_id: data[i + OFFSET_ID],
1595
- point_count: count,
1596
- point_count_abbreviated: abbrev
1597
- });
1598
- }
1599
-
1600
- const GEOJSONVT_CLIP_START = 'geojsonvt_clip_start';
1601
- const GEOJSONVT_CLIP_END = 'geojsonvt_clip_end';
1602
- /**
1603
- * Creates a tile object from the given features
1604
- * @param features - the features to include in the tile
1605
- * @param z
1606
- * @param tx
1607
- * @param ty
1608
- * @param options - the options object
1609
- * @returns the created tile
1610
- */
1611
- function createTile(features, z, tx, ty, options) {
1612
- const tolerance = z === options.maxZoom ? 0 : options.tolerance / ((1 << z) * options.extent);
1613
- const tile = {
1614
- transformed: false,
1615
- features: [],
1616
- source: null,
1617
- x: tx,
1618
- y: ty,
1619
- z: z,
1620
- minX: 2,
1621
- minY: 1,
1622
- maxX: -1,
1623
- maxY: 0,
1624
- numPoints: 0,
1625
- numSimplified: 0,
1626
- numFeatures: features.length
1627
- };
1628
- for (const feature of features) {
1629
- addFeature(tile, feature, tolerance, options);
1630
- }
1631
- return tile;
1632
- }
1633
- function addFeature(tile, feature, tolerance, options) {
1634
- tile.minX = Math.min(tile.minX, feature.minX);
1635
- tile.minY = Math.min(tile.minY, feature.minY);
1636
- tile.maxX = Math.max(tile.maxX, feature.maxX);
1637
- tile.maxY = Math.max(tile.maxY, feature.maxY);
1638
- switch (feature.type) {
1639
- case 'Point':
1640
- case 'MultiPoint':
1641
- addPointsTileFeature(tile, feature);
1642
- return;
1643
- case 'LineString':
1644
- addLineTileFeautre(tile, feature, tolerance, options);
1645
- return;
1646
- case 'MultiLineString':
1647
- case 'Polygon':
1648
- addLinesTileFeature(tile, feature, tolerance);
1649
- return;
1650
- case 'MultiPolygon':
1651
- addMultiPolygonTileFeature(tile, feature, tolerance);
1652
- return;
1653
- }
1654
- }
1655
- function addPointsTileFeature(tile, feature) {
1656
- const geometry = [];
1657
- for (let i = 0; i < feature.geometry.length; i += 3) {
1658
- geometry.push(feature.geometry[i], feature.geometry[i + 1]);
1659
- tile.numPoints++;
1660
- tile.numSimplified++;
1661
- }
1662
- if (!geometry.length)
1663
- return;
1664
- const tileFeature = {
1665
- type: 1,
1666
- tags: feature.tags || null,
1667
- geometry: geometry
1668
- };
1669
- if (feature.id !== null) {
1670
- tileFeature.id = feature.id;
1671
- }
1672
- tile.features.push(tileFeature);
1673
- }
1674
- function addLineTileFeautre(tile, feature, tolerance, options) {
1675
- const geometry = [];
1676
- addLine(geometry, feature.geometry, tile, tolerance, false, false);
1677
- if (!geometry.length)
1678
- return;
1679
- let tags = feature.tags || null;
1680
- if (options.lineMetrics) {
1681
- tags = {};
1682
- for (const key in feature.tags)
1683
- tags[key] = feature.tags[key];
1684
- tags[GEOJSONVT_CLIP_START] = feature.geometry.start / feature.geometry.size;
1685
- tags[GEOJSONVT_CLIP_END] = feature.geometry.end / feature.geometry.size;
1686
- }
1687
- const tileFeature = {
1688
- type: 2,
1689
- tags: tags,
1690
- geometry: geometry
1691
- };
1692
- if (feature.id !== null) {
1693
- tileFeature.id = feature.id;
1694
- }
1695
- tile.features.push(tileFeature);
1696
- }
1697
- function addLinesTileFeature(tile, feature, tolerance) {
1698
- const geometry = [];
1699
- for (let i = 0; i < feature.geometry.length; i++) {
1700
- addLine(geometry, feature.geometry[i], tile, tolerance, feature.type === 'Polygon', i === 0);
1701
- }
1702
- if (!geometry.length)
1703
- return;
1704
- const tileFeature = {
1705
- type: feature.type === 'Polygon' ? 3 : 2,
1706
- tags: feature.tags || null,
1707
- geometry: geometry
1708
- };
1709
- if (feature.id !== null) {
1710
- tileFeature.id = feature.id;
1711
- }
1712
- tile.features.push(tileFeature);
1713
- }
1714
- function addMultiPolygonTileFeature(tile, feature, tolerance) {
1715
- const geometry = [];
1716
- for (let k = 0; k < feature.geometry.length; k++) {
1717
- const polygon = feature.geometry[k];
1718
- for (let i = 0; i < polygon.length; i++) {
1719
- addLine(geometry, polygon[i], tile, tolerance, true, i === 0);
1720
- }
1721
- }
1722
- if (!geometry.length)
1723
- return;
1724
- const tileFeature = {
1725
- type: 3,
1726
- tags: feature.tags || null,
1727
- geometry: geometry
1728
- };
1729
- if (feature.id !== null) {
1730
- tileFeature.id = feature.id;
1731
- }
1732
- tile.features.push(tileFeature);
1733
- }
1734
- function addLine(result, geom, tile, tolerance, isPolygon, isOuter) {
1735
- const sqTolerance = tolerance * tolerance;
1736
- if (tolerance > 0 && (geom.size < (isPolygon ? sqTolerance : tolerance))) {
1737
- tile.numPoints += geom.points.length / 3;
1738
- return;
1739
- }
1740
- const ring = [];
1741
- for (let i = 0; i < geom.points.length; i += 3) {
1742
- if (tolerance === 0 || geom.points[i + 2] > sqTolerance) {
1743
- tile.numSimplified++;
1744
- ring.push(geom.points[i], geom.points[i + 1]);
1745
- }
1746
- tile.numPoints++;
1747
- }
1748
- if (isPolygon)
1749
- rewind(ring, isOuter);
1750
- result.push(ring);
1751
- }
1752
- function rewind(ring, clockwise) {
1753
- let area = 0;
1754
- for (let i = 0, len = ring.length, j = len - 2; i < len; j = i, i += 2) {
1755
- area += (ring[i] - ring[j]) * (ring[i + 1] + ring[j + 1]);
1756
- }
1757
- if (area > 0 !== clockwise)
1758
- return;
1759
- for (let i = 0, len = ring.length; i < len / 2; i += 2) {
1760
- const x = ring[i];
1761
- const y = ring[i + 1];
1762
- ring[i] = ring[len - 2 - i];
1763
- ring[i + 1] = ring[len - 1 - i];
1764
- ring[len - 2 - i] = x;
1765
- ring[len - 1 - i] = y;
1766
- }
1767
- }
1768
-
1769
- /**
1770
- * Transforms the coordinates of each feature in the given tile from
1771
- * mercator-projected space into (extent x extent) tile space.
1772
- * @param tile - the tile to transform, this gets modified in place
1773
- * @param extent - the tile extent (usually 4096)
1774
- * @returns the transformed tile
1775
- */
1776
- function transformTile(tile, extent) {
1777
- if (tile.transformed) {
1778
- return tile;
1779
- }
1780
- const z2 = 1 << tile.z;
1781
- const tx = tile.x;
1782
- const ty = tile.y;
1783
- for (const feature of tile.features) {
1784
- if (feature.type === 1) {
1785
- transformPointFeature(feature, extent, z2, tx, ty);
1786
- }
1787
- else {
1788
- transformNonPointFeature(feature, extent, z2, tx, ty);
1789
- }
1790
- }
1791
- tile.transformed = true;
1792
- return tile;
1793
- }
1794
- /**
1795
- * Transforms a single point feature from mercator-projected space into (extent x extent) tile space.
1796
- */
1797
- function transformPointFeature(feature, extent, z2, tx, ty) {
1798
- const transformed = feature;
1799
- const geometry = feature.geometry;
1800
- const point = [];
1801
- for (let i = 0; i < geometry.length; i += 2) {
1802
- point.push(transformPoint(geometry[i], geometry[i + 1], extent, z2, tx, ty));
1803
- }
1804
- transformed.geometry = point;
1805
- return transformed;
1806
- }
1807
- /**
1808
- * Transforms a single non-point feature from mercator-projected space into (extent x extent) tile space.
1809
- */
1810
- function transformNonPointFeature(feature, extent, z2, tx, ty) {
1811
- const transformed = feature;
1812
- const geometry = feature.geometry;
1813
- const nonPoint = [];
1814
- for (const geom of geometry) {
1815
- const ring = [];
1816
- for (let i = 0; i < geom.length; i += 2) {
1817
- ring.push(transformPoint(geom[i], geom[i + 1], extent, z2, tx, ty));
1818
- }
1819
- nonPoint.push(ring);
1820
- }
1821
- transformed.geometry = nonPoint;
1822
- return transformed;
1823
- }
1824
- function transformPoint(x, y, extent, z2, tx, ty) {
1825
- return [
1826
- Math.round(extent * (x * z2 - tx)),
1827
- Math.round(extent * (y * z2 - ty))
1828
- ];
1829
- }
1830
-
1831
- class TileIndex {
1832
- constructor(options) {
1833
- this.options = options;
1834
- /** @internal */
1835
- this.stats = {};
1836
- /** @internal */
1837
- this.total = 0;
1838
- this.tiles = {};
1839
- this.tileCoords = [];
1840
- this.stats = {};
1841
- this.total = 0;
1842
- }
1843
- initialize(features) {
1844
- // start slicing from the top tile down
1845
- this.splitTile(features, 0, 0, 0);
1846
- if (this.options.debug) {
1847
- if (features.length)
1848
- console.log('features: %d, points: %d', this.tiles[0].numFeatures, this.tiles[0].numPoints);
1849
- console.timeEnd('generate tiles');
1850
- console.log('tiles generated:', this.total, JSON.stringify(this.stats));
1851
- }
1852
- }
1853
- /** {@inheritdoc} */
1854
- updateIndex(source, affected, options) {
1855
- if (options.debug > 1) {
1856
- console.log('invalidating tiles');
1857
- console.time('invalidating');
1858
- }
1859
- this.invalidateTiles(affected);
1860
- if (options.debug > 1)
1861
- console.timeEnd('invalidating');
1862
- // re-generate root tile with updated feature set
1863
- const [z, x, y] = [0, 0, 0];
1864
- const rootTile = createTile(source, z, x, y, options);
1865
- rootTile.source = source;
1866
- // update tile index with new root tile - ready for getTile calls
1867
- const id = toID(z, x, y);
1868
- this.tiles[id] = rootTile;
1869
- this.tileCoords.push({ z, x, y, id });
1870
- if (options.debug) {
1871
- const key = `z${z}`;
1872
- this.stats[key] = (this.stats[key] || 0) + 1;
1873
- this.total++;
1874
- }
1875
- }
1876
- /** {@inheritdoc} */
1877
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
1878
- getClusterExpansionZoom(_clusterId) {
1879
- return null;
1880
- }
1881
- /** {@inheritdoc} */
1882
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
1883
- getChildren(_clusterId) {
1884
- return null;
1885
- }
1886
- /** {@inheritdoc} */
1887
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
1888
- getLeaves(_clusterId, _limit, _offset) {
1889
- return null;
1890
- }
1891
- /** {@inheritdoc} */
1892
- getTile(z, x, y) {
1893
- const { extent, debug } = this.options;
1894
- const z2 = 1 << z;
1895
- x = (x + z2) & (z2 - 1); // wrap tile x coordinate
1896
- const id = toID(z, x, y);
1897
- if (this.tiles[id]) {
1898
- return transformTile(this.tiles[id], extent);
1899
- }
1900
- if (debug > 1)
1901
- console.log('drilling down to z%d-%d-%d', z, x, y);
1902
- let z0 = z;
1903
- let x0 = x;
1904
- let y0 = y;
1905
- let parent;
1906
- while (!parent && z0 > 0) {
1907
- z0--;
1908
- x0 = x0 >> 1;
1909
- y0 = y0 >> 1;
1910
- parent = this.tiles[toID(z0, x0, y0)];
1911
- }
1912
- if (!parent?.source)
1913
- return null;
1914
- // if we found a parent tile containing the original geometry, we can drill down from it
1915
- if (debug > 1) {
1916
- console.log('found parent tile z%d-%d-%d', z0, x0, y0);
1917
- console.time('drilling down');
1918
- }
1919
- this.splitTile(parent.source, z0, x0, y0, z, x, y);
1920
- if (debug > 1)
1921
- console.timeEnd('drilling down');
1922
- if (!this.tiles[id])
1923
- return null;
1924
- return transformTile(this.tiles[id], extent);
1925
- }
1926
- /**
1927
- * splits features from a parent tile to sub-tiles.
1928
- * z, x, and y are the coordinates of the parent tile
1929
- * cz, cx, and cy are the coordinates of the target tile
1930
- *
1931
- * If no target tile is specified, splitting stops when we reach the maximum
1932
- * zoom or the number of points is low as specified in the options.
1933
- * @internal
1934
- * @param features - features to split
1935
- * @param z - tile zoom level
1936
- * @param x - tile x coordinate
1937
- * @param y - tile y coordinate
1938
- * @param cz - target tile zoom level
1939
- * @param cx - target tile x coordinate
1940
- * @param cy - target tile y coordinate
1941
- */
1942
- splitTile(features, z, x, y, cz, cx, cy) {
1943
- const stack = [features, z, x, y];
1944
- const options = this.options;
1945
- const debug = options.debug;
1946
- // avoid recursion by using a processing queue
1947
- while (stack.length) {
1948
- y = stack.pop();
1949
- x = stack.pop();
1950
- z = stack.pop();
1951
- features = stack.pop();
1952
- const z2 = 1 << z;
1953
- const id = toID(z, x, y);
1954
- let tile = this.tiles[id];
1955
- if (!tile) {
1956
- if (debug > 1)
1957
- console.time('creation');
1958
- tile = this.tiles[id] = createTile(features, z, x, y, options);
1959
- this.tileCoords.push({ z, x, y, id });
1960
- if (debug) {
1961
- if (debug > 1) {
1962
- console.log('tile z%d-%d-%d (features: %d, points: %d, simplified: %d)', z, x, y, tile.numFeatures, tile.numPoints, tile.numSimplified);
1963
- console.timeEnd('creation');
1964
- }
1965
- const key = `z${z}`;
1966
- this.stats[key] = (this.stats[key] || 0) + 1;
1967
- this.total++;
1968
- }
1969
- }
1970
- // save reference to original geometry in tile so that we can drill down later if we stop now
1971
- tile.source = features;
1972
- // if it's the first-pass tiling
1973
- if (cz == null) {
1974
- // stop tiling if we reached max zoom, or if the tile is too simple
1975
- if (z === options.indexMaxZoom || tile.numPoints <= options.indexMaxPoints)
1976
- continue;
1977
- // if a drilldown to a specific tile
1978
- }
1979
- else if (z === options.maxZoom || z === cz) {
1980
- // stop tiling if we reached base zoom or our target tile zoom
1981
- continue;
1982
- }
1983
- else if (cz != null) {
1984
- // stop tiling if it's not an ancestor of the target tile
1985
- const zoomSteps = cz - z;
1986
- if (x !== cx >> zoomSteps || y !== cy >> zoomSteps)
1987
- continue;
1988
- }
1989
- // if we slice further down, no need to keep source geometry
1990
- tile.source = null;
1991
- if (!features.length)
1992
- continue;
1993
- if (debug > 1)
1994
- console.time('clipping');
1995
- // values we'll use for clipping
1996
- const k1 = 0.5 * options.buffer / options.extent;
1997
- const k2 = 0.5 - k1;
1998
- const k3 = 0.5 + k1;
1999
- const k4 = 1 + k1;
2000
- let tl = null;
2001
- let bl = null;
2002
- let tr = null;
2003
- let br = null;
2004
- const left = clip(features, z2, x - k1, x + k3, AxisType.X, tile.minX, tile.maxX, options);
2005
- const right = clip(features, z2, x + k2, x + k4, AxisType.X, tile.minX, tile.maxX, options);
2006
- if (left) {
2007
- tl = clip(left, z2, y - k1, y + k3, AxisType.Y, tile.minY, tile.maxY, options);
2008
- bl = clip(left, z2, y + k2, y + k4, AxisType.Y, tile.minY, tile.maxY, options);
2009
- }
2010
- if (right) {
2011
- tr = clip(right, z2, y - k1, y + k3, AxisType.Y, tile.minY, tile.maxY, options);
2012
- br = clip(right, z2, y + k2, y + k4, AxisType.Y, tile.minY, tile.maxY, options);
2013
- }
2014
- if (debug > 1)
2015
- console.timeEnd('clipping');
2016
- stack.push(tl || [], z + 1, x * 2, y * 2);
2017
- stack.push(bl || [], z + 1, x * 2, y * 2 + 1);
2018
- stack.push(tr || [], z + 1, x * 2 + 1, y * 2);
2019
- stack.push(br || [], z + 1, x * 2 + 1, y * 2 + 1);
2020
- }
2021
- }
2022
- /**
2023
- * Invalidates (removes) tiles affected by the provided features
2024
- * @internal
2025
- * @param features
2026
- */
2027
- invalidateTiles(features) {
2028
- if (!features.length)
2029
- return;
2030
- const options = this.options;
2031
- const { debug } = options;
2032
- // calculate bounding box of all features for trivial reject
2033
- let minX = Infinity;
2034
- let maxX = -Infinity;
2035
- let minY = Infinity;
2036
- let maxY = -Infinity;
2037
- for (const feature of features) {
2038
- minX = Math.min(minX, feature.minX);
2039
- maxX = Math.max(maxX, feature.maxX);
2040
- minY = Math.min(minY, feature.minY);
2041
- maxY = Math.max(maxY, feature.maxY);
2042
- }
2043
- // tile buffer clipping value - not halved as in splitTile above because checking against tile's own extent
2044
- const k1 = options.buffer / options.extent;
2045
- // track removed tile ids for o(1) lookup
2046
- const removedLookup = new Set();
2047
- // iterate through existing tiles and remove ones that are affected by features
2048
- for (const id in this.tiles) {
2049
- const tile = this.tiles[id];
2050
- // calculate tile bounds including buffer
2051
- const z2 = 1 << tile.z;
2052
- const tileMinX = (tile.x - k1) / z2;
2053
- const tileMaxX = (tile.x + 1 + k1) / z2;
2054
- const tileMinY = (tile.y - k1) / z2;
2055
- const tileMaxY = (tile.y + 1 + k1) / z2;
2056
- // trivial reject if feature bounds don't intersect tile
2057
- if (maxX < tileMinX || minX >= tileMaxX ||
2058
- maxY < tileMinY || minY >= tileMaxY) {
2059
- continue;
2060
- }
2061
- // check if any feature intersects with the tile
2062
- let intersects = false;
2063
- for (const feature of features) {
2064
- if (feature.maxX >= tileMinX && feature.minX < tileMaxX &&
2065
- feature.maxY >= tileMinY && feature.minY < tileMaxY) {
2066
- intersects = true;
2067
- break;
2068
- }
2069
- }
2070
- if (!intersects)
2071
- continue;
2072
- if (debug) {
2073
- if (debug > 1) {
2074
- 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);
2075
- }
2076
- const key = `z${tile.z}`;
2077
- this.stats[key] = (this.stats[key] || 0) - 1;
2078
- this.total--;
2079
- }
2080
- delete this.tiles[id];
2081
- removedLookup.add(id);
2082
- }
2083
- // remove tile coords that are no longer in the index
2084
- if (removedLookup.size) {
2085
- this.tileCoords = this.tileCoords.filter(c => !removedLookup.has(c.id));
2086
- }
2087
- }
2088
- }
2089
- function toID(z, x, y) {
2090
- return (((1 << z) * y + x) * 32) + z;
2091
- }
2092
-
2093
- const defaultOptions = {
2094
- maxZoom: 14,
2095
- indexMaxZoom: 5,
2096
- indexMaxPoints: 100000,
2097
- tolerance: 3,
2098
- extent: 4096,
2099
- buffer: 64,
2100
- lineMetrics: false,
2101
- promoteId: null,
2102
- generateId: false,
2103
- updateable: false,
2104
- cluster: false,
2105
- clusterOptions: defaultClusterOptions,
2106
- debug: 0
2107
- };
2108
- /**
2109
- * Main class for creating and managing a vector tile index from GeoJSON data.
2110
- */
2111
- class GeoJSONVT {
2112
- /**
2113
- * @internal
2114
- * This is for the tests
2115
- */
2116
- get tiles() {
2117
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2118
- return this.tileIndex?.tiles ?? {};
2119
- }
2120
- /**
2121
- * @internal
2122
- * This is for the tests
2123
- */
2124
- get stats() {
2125
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2126
- return this.tileIndex.stats;
2127
- }
2128
- /**
2129
- * @internal
2130
- * This is for the tests
2131
- */
2132
- get total() {
2133
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2134
- return this.tileIndex.total;
2135
- }
2136
- constructor(data, options) {
2137
- options = this.options = Object.assign({}, defaultOptions, options);
2138
- const debug = options.debug;
2139
- if (debug)
2140
- console.time('preprocess data');
2141
- if (options.maxZoom < 0 || options.maxZoom > 24)
2142
- throw new Error('maxZoom should be in the 0-24 range');
2143
- if (options.promoteId && options.generateId)
2144
- throw new Error('promoteId and generateId cannot be used together.');
2145
- // projects and adds simplification info
2146
- let features = convertToInternal(data, options);
2147
- if (debug) {
2148
- console.timeEnd('preprocess data');
2149
- console.log('index: maxZoom: %d, maxPoints: %d', options.indexMaxZoom, options.indexMaxPoints);
2150
- console.time('generate tiles');
2151
- }
2152
- // wraps features (ie extreme west and extreme east)
2153
- features = wrap(features, options);
2154
- // for updateable indexes, store a copy of the original simplified features
2155
- if (options.updateable) {
2156
- this.source = features;
2157
- }
2158
- this.initializeIndex(features, options);
2159
- }
2160
- initializeIndex(features, options) {
2161
- this.tileIndex = options.cluster ? new ClusterTileIndex(options.clusterOptions) : new TileIndex(options);
2162
- if (!features.length)
2163
- return;
2164
- this.tileIndex.initialize(features);
2165
- }
2166
- /**
2167
- * Given z, x, and y tile coordinates, returns the corresponding tile with geometries in tile coordinates, much like MVT data is stored.
2168
- * @param z - tile zoom level
2169
- * @param x - tile x coordinate
2170
- * @param y - tile y coordinate
2171
- * @returns the transformed tile or null if not found
2172
- */
2173
- getTile(z, x, y) {
2174
- z = +z;
2175
- x = +x;
2176
- y = +y;
2177
- if (z < 0 || z > 24)
2178
- return null;
2179
- return this.tileIndex.getTile(z, x, y);
2180
- }
2181
- /**
2182
- * Updates the source data feature set using a {@link GeoJSONVTSourceDiff}
2183
- * @param diff - the source diff object
2184
- */
2185
- updateData(diff, filter) {
2186
- const options = this.options;
2187
- if (!options.updateable)
2188
- throw new Error('to update tile geojson `updateable` option must be set to true');
2189
- // apply diff and collect affected features and updated source that will be used to invalidate tiles
2190
- let { affected, source } = applySourceDiff(this.source, diff, options);
2191
- if (filter) {
2192
- ({ affected, source } = this.filterUpdate(source, affected, filter));
2193
- }
2194
- // nothing has changed
2195
- if (!affected.length)
2196
- return;
2197
- // update source with new simplified feature set
2198
- this.source = source;
2199
- this.tileIndex.updateIndex(source, affected, options);
2200
- }
2201
- /**
2202
- * Filter an update using a predicate function. Returns the affected and updated source features.
2203
- */
2204
- filterUpdate(source, affected, predicate) {
2205
- const removeIds = new Set();
2206
- for (const feature of source) {
2207
- if (feature.id == undefined)
2208
- continue;
2209
- if (predicate(featureToGeoJSON(feature)))
2210
- continue;
2211
- affected.push(feature);
2212
- removeIds.add(feature.id);
2213
- }
2214
- source = source.filter(feature => !removeIds.has(feature.id));
2215
- return { affected, source };
2216
- }
2217
- /**
2218
- * Returns source data as GeoJSON - only available when `updateable` option is set to true.
2219
- */
2220
- getData() {
2221
- if (!this.options.updateable)
2222
- throw new Error('to retrieve data the `updateable` option must be set to true');
2223
- return convertToGeoJSON(this.source);
2224
- }
2225
- /**
2226
- * Update supercluster options and regenerate the index.
2227
- * @param cluster - whether to enable clustering
2228
- * @param clusterOptions - {@link SuperclusterOptions}
2229
- */
2230
- updateClusterOptions(cluster, clusterOptions) {
2231
- const wasCluster = this.options.cluster;
2232
- this.options.cluster = cluster;
2233
- this.options.clusterOptions = clusterOptions;
2234
- if (wasCluster == cluster) {
2235
- this.tileIndex.updateIndex(this.source, [], this.options);
2236
- return;
2237
- }
2238
- this.initializeIndex(this.source, this.options);
2239
- }
2240
- /**
2241
- * Returns the zoom level at which a cluster expands into multiple children.
2242
- * @param clusterId - The target cluster id.
2243
- * @returns the expansion zoom or null in case of non-clustered source
2244
- */
2245
- getClusterExpansionZoom(clusterId) {
2246
- return this.tileIndex.getClusterExpansionZoom(clusterId);
2247
- }
2248
- /**
2249
- * Returns the immediate children (clusters or points) of a cluster as GeoJSON.
2250
- * @param clusterId - The target cluster id.
2251
- * @returns the immediate children or null in case of non-clustered source
2252
- */
2253
- getClusterChildren(clusterId) {
2254
- return this.tileIndex.getChildren(clusterId);
2255
- }
2256
- /**
2257
- * Returns leaf point features under a cluster, paginated by `limit` and `offset`.
2258
- * @param clusterId - The target cluster id.
2259
- * @param limit - Maximum number of points to return (defaults to `10`).
2260
- * @param offset - Number of points to skip before collecting results (defaults to `0`).
2261
- * @returns leaf point features under a cluster or null in case of non-clustered source
2262
- */
2263
- getClusterLeaves(clusterId, limit, offset) {
2264
- return this.tileIndex.getLeaves(clusterId, limit, offset);
2265
- }
2266
- }
2267
-
2268
- /**
2269
- * Converts GeoJSON data directly to a single vector tile without building a tile index.
2270
- *
2271
- * Unlike the {@link GeoJSONVT} class which builds a hierarchical tile index for efficient
2272
- * repeated tile access, this function generates a single tile on-demand. This is useful when:
2273
- * - You only need one specific tile and don't need to query multiple tiles
2274
- * - The source data is already spatially filtered to the tile's bounding box
2275
- * - You want to avoid the overhead of building a full tile index
2276
- *
2277
- * @example
2278
- * ```ts
2279
- * import {geoJSONToTile} from '@maplibre/geojson-vt';
2280
- *
2281
- * const geojson = {
2282
- * type: 'FeatureCollection',
2283
- * features: [{
2284
- * type: 'Feature',
2285
- * geometry: { type: 'Point', coordinates: [-77.03, 38.90] },
2286
- * properties: { name: 'Washington, D.C.' }
2287
- * }]
2288
- * };
2289
- *
2290
- * const tile = geoJSONToTile(geojson, 10, 292, 391, { extent: 4096 });
2291
- * ```
2292
- *
2293
- * @param data - GeoJSON data (Feature, FeatureCollection, or Geometry)
2294
- * @param z - Tile zoom level
2295
- * @param x - Tile x coordinate
2296
- * @param y - Tile y coordinate
2297
- * @param options - Optional configuration for tile generation
2298
- * @returns The generated tile with geometries in tile coordinates, or null if no features
2299
- */
2300
- function geoJSONToTile(data, z, x, y, options = {}) {
2301
- options = { ...defaultOptions, ...options };
2302
- const { wrap: shouldWrap = false, clip: shouldClip = false } = options;
2303
- let features = convertToInternal(data, options);
2304
- if (shouldWrap) {
2305
- features = wrap(features, options);
2306
- }
2307
- if (shouldClip || options.lineMetrics) {
2308
- const pow2 = 1 << z;
2309
- const buffer = options.buffer / options.extent;
2310
- const left = clip(features, pow2, (x - buffer), (x + 1 + buffer), AxisType.X, -1, 2, options);
2311
- features = clip(left || [], pow2, (y - buffer), (y + 1 + buffer), AxisType.Y, -1, 2, options);
2312
- }
2313
- return transformTile(createTile(features ?? [], z, x, y, options), options.extent);
2314
- }
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
+ }
2315
1988
 
1989
+ //#endregion
2316
1990
  exports.GEOJSONVT_CLIP_END = GEOJSONVT_CLIP_END;
2317
1991
  exports.GEOJSONVT_CLIP_START = GEOJSONVT_CLIP_START;
2318
1992
  exports.GeoJSONVT = GeoJSONVT;
2319
1993
  exports.Supercluster = ClusterTileIndex;
2320
1994
  exports.geoJSONToTile = geoJSONToTile;
2321
-
2322
- }));
1995
+ });