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