@maplibre/geojson-vt 6.1.0 → 6.1.2

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