@classic-homes/maps-core 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1138 @@
1
+ // src/utils/bounds.ts
2
+ function calculateBounds(geojson) {
3
+ let minLng = Infinity;
4
+ let maxLng = -Infinity;
5
+ let minLat = Infinity;
6
+ let maxLat = -Infinity;
7
+ let hasCoordinates = false;
8
+ function processCoordinate(coord) {
9
+ const [lng, lat] = coord;
10
+ if (typeof lng === "number" && typeof lat === "number" && isFinite(lng) && isFinite(lat)) {
11
+ minLng = Math.min(minLng, lng);
12
+ maxLng = Math.max(maxLng, lng);
13
+ minLat = Math.min(minLat, lat);
14
+ maxLat = Math.max(maxLat, lat);
15
+ hasCoordinates = true;
16
+ }
17
+ }
18
+ function processGeometry(geometry) {
19
+ if (!geometry) return;
20
+ switch (geometry.type) {
21
+ case "Point":
22
+ processCoordinate(geometry.coordinates);
23
+ break;
24
+ case "MultiPoint":
25
+ case "LineString":
26
+ geometry.coordinates.forEach(processCoordinate);
27
+ break;
28
+ case "MultiLineString":
29
+ case "Polygon":
30
+ geometry.coordinates.forEach((ring) => ring.forEach(processCoordinate));
31
+ break;
32
+ case "MultiPolygon":
33
+ geometry.coordinates.forEach(
34
+ (polygon) => polygon.forEach((ring) => ring.forEach(processCoordinate))
35
+ );
36
+ break;
37
+ }
38
+ }
39
+ if (geojson.type === "FeatureCollection") {
40
+ geojson.features.forEach((feature) => processGeometry(feature.geometry));
41
+ } else if (geojson.type === "Feature") {
42
+ processGeometry(geojson.geometry);
43
+ }
44
+ if (!hasCoordinates) {
45
+ return null;
46
+ }
47
+ return [
48
+ [minLng, minLat],
49
+ // Southwest
50
+ [maxLng, maxLat]
51
+ // Northeast
52
+ ];
53
+ }
54
+
55
+ // ../../node_modules/quickselect/index.js
56
+ function quickselect(arr, k, left = 0, right = arr.length - 1, compare = defaultCompare) {
57
+ while (right > left) {
58
+ if (right - left > 600) {
59
+ const n = right - left + 1;
60
+ const m = k - left + 1;
61
+ const z = Math.log(n);
62
+ const s = 0.5 * Math.exp(2 * z / 3);
63
+ const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
64
+ const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
65
+ const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
66
+ quickselect(arr, k, newLeft, newRight, compare);
67
+ }
68
+ const t = arr[k];
69
+ let i = left;
70
+ let j = right;
71
+ swap(arr, left, k);
72
+ if (compare(arr[right], t) > 0) swap(arr, left, right);
73
+ while (i < j) {
74
+ swap(arr, i, j);
75
+ i++;
76
+ j--;
77
+ while (compare(arr[i], t) < 0) i++;
78
+ while (compare(arr[j], t) > 0) j--;
79
+ }
80
+ if (compare(arr[left], t) === 0) swap(arr, left, j);
81
+ else {
82
+ j++;
83
+ swap(arr, j, right);
84
+ }
85
+ if (j <= k) left = j + 1;
86
+ if (k <= j) right = j - 1;
87
+ }
88
+ }
89
+ function swap(arr, i, j) {
90
+ const tmp = arr[i];
91
+ arr[i] = arr[j];
92
+ arr[j] = tmp;
93
+ }
94
+ function defaultCompare(a, b) {
95
+ return a < b ? -1 : a > b ? 1 : 0;
96
+ }
97
+
98
+ // ../../node_modules/rbush/index.js
99
+ var RBush = class {
100
+ constructor(maxEntries = 9) {
101
+ this._maxEntries = Math.max(4, maxEntries);
102
+ this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));
103
+ this.clear();
104
+ }
105
+ all() {
106
+ return this._all(this.data, []);
107
+ }
108
+ search(bbox) {
109
+ let node = this.data;
110
+ const result = [];
111
+ if (!intersects(bbox, node)) return result;
112
+ const toBBox = this.toBBox;
113
+ const nodesToSearch = [];
114
+ while (node) {
115
+ for (let i = 0; i < node.children.length; i++) {
116
+ const child = node.children[i];
117
+ const childBBox = node.leaf ? toBBox(child) : child;
118
+ if (intersects(bbox, childBBox)) {
119
+ if (node.leaf) result.push(child);
120
+ else if (contains(bbox, childBBox)) this._all(child, result);
121
+ else nodesToSearch.push(child);
122
+ }
123
+ }
124
+ node = nodesToSearch.pop();
125
+ }
126
+ return result;
127
+ }
128
+ collides(bbox) {
129
+ let node = this.data;
130
+ if (!intersects(bbox, node)) return false;
131
+ const nodesToSearch = [];
132
+ while (node) {
133
+ for (let i = 0; i < node.children.length; i++) {
134
+ const child = node.children[i];
135
+ const childBBox = node.leaf ? this.toBBox(child) : child;
136
+ if (intersects(bbox, childBBox)) {
137
+ if (node.leaf || contains(bbox, childBBox)) return true;
138
+ nodesToSearch.push(child);
139
+ }
140
+ }
141
+ node = nodesToSearch.pop();
142
+ }
143
+ return false;
144
+ }
145
+ load(data) {
146
+ if (!(data && data.length)) return this;
147
+ if (data.length < this._minEntries) {
148
+ for (let i = 0; i < data.length; i++) {
149
+ this.insert(data[i]);
150
+ }
151
+ return this;
152
+ }
153
+ let node = this._build(data.slice(), 0, data.length - 1, 0);
154
+ if (!this.data.children.length) {
155
+ this.data = node;
156
+ } else if (this.data.height === node.height) {
157
+ this._splitRoot(this.data, node);
158
+ } else {
159
+ if (this.data.height < node.height) {
160
+ const tmpNode = this.data;
161
+ this.data = node;
162
+ node = tmpNode;
163
+ }
164
+ this._insert(node, this.data.height - node.height - 1, true);
165
+ }
166
+ return this;
167
+ }
168
+ insert(item) {
169
+ if (item) this._insert(item, this.data.height - 1);
170
+ return this;
171
+ }
172
+ clear() {
173
+ this.data = createNode([]);
174
+ return this;
175
+ }
176
+ remove(item, equalsFn) {
177
+ if (!item) return this;
178
+ let node = this.data;
179
+ const bbox = this.toBBox(item);
180
+ const path = [];
181
+ const indexes = [];
182
+ let i, parent, goingUp;
183
+ while (node || path.length) {
184
+ if (!node) {
185
+ node = path.pop();
186
+ parent = path[path.length - 1];
187
+ i = indexes.pop();
188
+ goingUp = true;
189
+ }
190
+ if (node.leaf) {
191
+ const index = findItem(item, node.children, equalsFn);
192
+ if (index !== -1) {
193
+ node.children.splice(index, 1);
194
+ path.push(node);
195
+ this._condense(path);
196
+ return this;
197
+ }
198
+ }
199
+ if (!goingUp && !node.leaf && contains(node, bbox)) {
200
+ path.push(node);
201
+ indexes.push(i);
202
+ i = 0;
203
+ parent = node;
204
+ node = node.children[0];
205
+ } else if (parent) {
206
+ i++;
207
+ node = parent.children[i];
208
+ goingUp = false;
209
+ } else node = null;
210
+ }
211
+ return this;
212
+ }
213
+ toBBox(item) {
214
+ return item;
215
+ }
216
+ compareMinX(a, b) {
217
+ return a.minX - b.minX;
218
+ }
219
+ compareMinY(a, b) {
220
+ return a.minY - b.minY;
221
+ }
222
+ toJSON() {
223
+ return this.data;
224
+ }
225
+ fromJSON(data) {
226
+ this.data = data;
227
+ return this;
228
+ }
229
+ _all(node, result) {
230
+ const nodesToSearch = [];
231
+ while (node) {
232
+ if (node.leaf) result.push(...node.children);
233
+ else nodesToSearch.push(...node.children);
234
+ node = nodesToSearch.pop();
235
+ }
236
+ return result;
237
+ }
238
+ _build(items, left, right, height) {
239
+ const N = right - left + 1;
240
+ let M = this._maxEntries;
241
+ let node;
242
+ if (N <= M) {
243
+ node = createNode(items.slice(left, right + 1));
244
+ calcBBox(node, this.toBBox);
245
+ return node;
246
+ }
247
+ if (!height) {
248
+ height = Math.ceil(Math.log(N) / Math.log(M));
249
+ M = Math.ceil(N / Math.pow(M, height - 1));
250
+ }
251
+ node = createNode([]);
252
+ node.leaf = false;
253
+ node.height = height;
254
+ const N2 = Math.ceil(N / M);
255
+ const N1 = N2 * Math.ceil(Math.sqrt(M));
256
+ multiSelect(items, left, right, N1, this.compareMinX);
257
+ for (let i = left; i <= right; i += N1) {
258
+ const right2 = Math.min(i + N1 - 1, right);
259
+ multiSelect(items, i, right2, N2, this.compareMinY);
260
+ for (let j = i; j <= right2; j += N2) {
261
+ const right3 = Math.min(j + N2 - 1, right2);
262
+ node.children.push(this._build(items, j, right3, height - 1));
263
+ }
264
+ }
265
+ calcBBox(node, this.toBBox);
266
+ return node;
267
+ }
268
+ _chooseSubtree(bbox, node, level, path) {
269
+ while (true) {
270
+ path.push(node);
271
+ if (node.leaf || path.length - 1 === level) break;
272
+ let minArea = Infinity;
273
+ let minEnlargement = Infinity;
274
+ let targetNode;
275
+ for (let i = 0; i < node.children.length; i++) {
276
+ const child = node.children[i];
277
+ const area = bboxArea(child);
278
+ const enlargement = enlargedArea(bbox, child) - area;
279
+ if (enlargement < minEnlargement) {
280
+ minEnlargement = enlargement;
281
+ minArea = area < minArea ? area : minArea;
282
+ targetNode = child;
283
+ } else if (enlargement === minEnlargement) {
284
+ if (area < minArea) {
285
+ minArea = area;
286
+ targetNode = child;
287
+ }
288
+ }
289
+ }
290
+ node = targetNode || node.children[0];
291
+ }
292
+ return node;
293
+ }
294
+ _insert(item, level, isNode) {
295
+ const bbox = isNode ? item : this.toBBox(item);
296
+ const insertPath = [];
297
+ const node = this._chooseSubtree(bbox, this.data, level, insertPath);
298
+ node.children.push(item);
299
+ extend(node, bbox);
300
+ while (level >= 0) {
301
+ if (insertPath[level].children.length > this._maxEntries) {
302
+ this._split(insertPath, level);
303
+ level--;
304
+ } else break;
305
+ }
306
+ this._adjustParentBBoxes(bbox, insertPath, level);
307
+ }
308
+ // split overflowed node into two
309
+ _split(insertPath, level) {
310
+ const node = insertPath[level];
311
+ const M = node.children.length;
312
+ const m = this._minEntries;
313
+ this._chooseSplitAxis(node, m, M);
314
+ const splitIndex = this._chooseSplitIndex(node, m, M);
315
+ const newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));
316
+ newNode.height = node.height;
317
+ newNode.leaf = node.leaf;
318
+ calcBBox(node, this.toBBox);
319
+ calcBBox(newNode, this.toBBox);
320
+ if (level) insertPath[level - 1].children.push(newNode);
321
+ else this._splitRoot(node, newNode);
322
+ }
323
+ _splitRoot(node, newNode) {
324
+ this.data = createNode([node, newNode]);
325
+ this.data.height = node.height + 1;
326
+ this.data.leaf = false;
327
+ calcBBox(this.data, this.toBBox);
328
+ }
329
+ _chooseSplitIndex(node, m, M) {
330
+ let index;
331
+ let minOverlap = Infinity;
332
+ let minArea = Infinity;
333
+ for (let i = m; i <= M - m; i++) {
334
+ const bbox1 = distBBox(node, 0, i, this.toBBox);
335
+ const bbox2 = distBBox(node, i, M, this.toBBox);
336
+ const overlap = intersectionArea(bbox1, bbox2);
337
+ const area = bboxArea(bbox1) + bboxArea(bbox2);
338
+ if (overlap < minOverlap) {
339
+ minOverlap = overlap;
340
+ index = i;
341
+ minArea = area < minArea ? area : minArea;
342
+ } else if (overlap === minOverlap) {
343
+ if (area < minArea) {
344
+ minArea = area;
345
+ index = i;
346
+ }
347
+ }
348
+ }
349
+ return index || M - m;
350
+ }
351
+ // sorts node children by the best axis for split
352
+ _chooseSplitAxis(node, m, M) {
353
+ const compareMinX = node.leaf ? this.compareMinX : compareNodeMinX;
354
+ const compareMinY = node.leaf ? this.compareMinY : compareNodeMinY;
355
+ const xMargin = this._allDistMargin(node, m, M, compareMinX);
356
+ const yMargin = this._allDistMargin(node, m, M, compareMinY);
357
+ if (xMargin < yMargin) node.children.sort(compareMinX);
358
+ }
359
+ // total margin of all possible split distributions where each node is at least m full
360
+ _allDistMargin(node, m, M, compare) {
361
+ node.children.sort(compare);
362
+ const toBBox = this.toBBox;
363
+ const leftBBox = distBBox(node, 0, m, toBBox);
364
+ const rightBBox = distBBox(node, M - m, M, toBBox);
365
+ let margin = bboxMargin(leftBBox) + bboxMargin(rightBBox);
366
+ for (let i = m; i < M - m; i++) {
367
+ const child = node.children[i];
368
+ extend(leftBBox, node.leaf ? toBBox(child) : child);
369
+ margin += bboxMargin(leftBBox);
370
+ }
371
+ for (let i = M - m - 1; i >= m; i--) {
372
+ const child = node.children[i];
373
+ extend(rightBBox, node.leaf ? toBBox(child) : child);
374
+ margin += bboxMargin(rightBBox);
375
+ }
376
+ return margin;
377
+ }
378
+ _adjustParentBBoxes(bbox, path, level) {
379
+ for (let i = level; i >= 0; i--) {
380
+ extend(path[i], bbox);
381
+ }
382
+ }
383
+ _condense(path) {
384
+ for (let i = path.length - 1, siblings; i >= 0; i--) {
385
+ if (path[i].children.length === 0) {
386
+ if (i > 0) {
387
+ siblings = path[i - 1].children;
388
+ siblings.splice(siblings.indexOf(path[i]), 1);
389
+ } else this.clear();
390
+ } else calcBBox(path[i], this.toBBox);
391
+ }
392
+ }
393
+ };
394
+ function findItem(item, items, equalsFn) {
395
+ if (!equalsFn) return items.indexOf(item);
396
+ for (let i = 0; i < items.length; i++) {
397
+ if (equalsFn(item, items[i])) return i;
398
+ }
399
+ return -1;
400
+ }
401
+ function calcBBox(node, toBBox) {
402
+ distBBox(node, 0, node.children.length, toBBox, node);
403
+ }
404
+ function distBBox(node, k, p, toBBox, destNode) {
405
+ if (!destNode) destNode = createNode(null);
406
+ destNode.minX = Infinity;
407
+ destNode.minY = Infinity;
408
+ destNode.maxX = -Infinity;
409
+ destNode.maxY = -Infinity;
410
+ for (let i = k; i < p; i++) {
411
+ const child = node.children[i];
412
+ extend(destNode, node.leaf ? toBBox(child) : child);
413
+ }
414
+ return destNode;
415
+ }
416
+ function extend(a, b) {
417
+ a.minX = Math.min(a.minX, b.minX);
418
+ a.minY = Math.min(a.minY, b.minY);
419
+ a.maxX = Math.max(a.maxX, b.maxX);
420
+ a.maxY = Math.max(a.maxY, b.maxY);
421
+ return a;
422
+ }
423
+ function compareNodeMinX(a, b) {
424
+ return a.minX - b.minX;
425
+ }
426
+ function compareNodeMinY(a, b) {
427
+ return a.minY - b.minY;
428
+ }
429
+ function bboxArea(a) {
430
+ return (a.maxX - a.minX) * (a.maxY - a.minY);
431
+ }
432
+ function bboxMargin(a) {
433
+ return a.maxX - a.minX + (a.maxY - a.minY);
434
+ }
435
+ function enlargedArea(a, b) {
436
+ return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) * (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));
437
+ }
438
+ function intersectionArea(a, b) {
439
+ const minX = Math.max(a.minX, b.minX);
440
+ const minY = Math.max(a.minY, b.minY);
441
+ const maxX = Math.min(a.maxX, b.maxX);
442
+ const maxY = Math.min(a.maxY, b.maxY);
443
+ return Math.max(0, maxX - minX) * Math.max(0, maxY - minY);
444
+ }
445
+ function contains(a, b) {
446
+ return a.minX <= b.minX && a.minY <= b.minY && b.maxX <= a.maxX && b.maxY <= a.maxY;
447
+ }
448
+ function intersects(a, b) {
449
+ return b.minX <= a.maxX && b.minY <= a.maxY && b.maxX >= a.minX && b.maxY >= a.minY;
450
+ }
451
+ function createNode(children) {
452
+ return {
453
+ children,
454
+ height: 1,
455
+ leaf: true,
456
+ minX: Infinity,
457
+ minY: Infinity,
458
+ maxX: -Infinity,
459
+ maxY: -Infinity
460
+ };
461
+ }
462
+ function multiSelect(arr, left, right, n, compare) {
463
+ const stack = [left, right];
464
+ while (stack.length) {
465
+ right = stack.pop();
466
+ left = stack.pop();
467
+ if (right - left <= n) continue;
468
+ const mid = left + Math.ceil((right - left) / n / 2) * n;
469
+ quickselect(arr, mid, left, right, compare);
470
+ stack.push(left, mid, mid, right);
471
+ }
472
+ }
473
+
474
+ // src/utils/spatial.ts
475
+ function buildSpatialIndex(geojson, options = {}) {
476
+ const { targetCells = 100, minCellSize = 1e-3 } = options;
477
+ const bounds = calculateBounds(geojson);
478
+ if (!bounds) {
479
+ return {
480
+ grid: /* @__PURE__ */ new Map(),
481
+ cols: 0,
482
+ rows: 0,
483
+ bounds: [
484
+ [0, 0],
485
+ [0, 0]
486
+ ],
487
+ cellWidth: 0,
488
+ cellHeight: 0,
489
+ featureCount: 0
490
+ };
491
+ }
492
+ const [[minLng, minLat], [maxLng, maxLat]] = bounds;
493
+ const width = maxLng - minLng;
494
+ const height = maxLat - minLat;
495
+ const aspectRatio = width / height;
496
+ let cols = Math.ceil(Math.sqrt(targetCells * aspectRatio));
497
+ let rows = Math.ceil(targetCells / cols);
498
+ const cellWidth = Math.max(width / cols, minCellSize);
499
+ const cellHeight = Math.max(height / rows, minCellSize);
500
+ cols = Math.ceil(width / cellWidth);
501
+ rows = Math.ceil(height / cellHeight);
502
+ const grid = /* @__PURE__ */ new Map();
503
+ for (const feature of geojson.features) {
504
+ const featureBounds = getFeatureBounds(feature);
505
+ if (!featureBounds) continue;
506
+ const [[fMinLng, fMinLat], [fMaxLng, fMaxLat]] = featureBounds;
507
+ const minCol = Math.max(0, Math.floor((fMinLng - minLng) / cellWidth));
508
+ const maxCol = Math.min(cols - 1, Math.floor((fMaxLng - minLng) / cellWidth));
509
+ const minRow = Math.max(0, Math.floor((fMinLat - minLat) / cellHeight));
510
+ const maxRow = Math.min(rows - 1, Math.floor((fMaxLat - minLat) / cellHeight));
511
+ for (let col = minCol; col <= maxCol; col++) {
512
+ for (let row = minRow; row <= maxRow; row++) {
513
+ const key = `${col},${row}`;
514
+ if (!grid.has(key)) {
515
+ grid.set(key, { features: [] });
516
+ }
517
+ grid.get(key).features.push(feature);
518
+ }
519
+ }
520
+ }
521
+ return {
522
+ grid,
523
+ cols,
524
+ rows,
525
+ bounds,
526
+ cellWidth,
527
+ cellHeight,
528
+ featureCount: geojson.features.length
529
+ };
530
+ }
531
+ function getFeatureBounds(feature) {
532
+ const geometry = feature.geometry;
533
+ if (!geometry) return null;
534
+ let minLng = Infinity;
535
+ let minLat = Infinity;
536
+ let maxLng = -Infinity;
537
+ let maxLat = -Infinity;
538
+ function processCoord(coord) {
539
+ minLng = Math.min(minLng, coord[0]);
540
+ minLat = Math.min(minLat, coord[1]);
541
+ maxLng = Math.max(maxLng, coord[0]);
542
+ maxLat = Math.max(maxLat, coord[1]);
543
+ }
544
+ function processRing(ring) {
545
+ ring.forEach(processCoord);
546
+ }
547
+ switch (geometry.type) {
548
+ case "Point":
549
+ processCoord(geometry.coordinates);
550
+ break;
551
+ case "MultiPoint":
552
+ case "LineString":
553
+ geometry.coordinates.forEach(processCoord);
554
+ break;
555
+ case "MultiLineString":
556
+ case "Polygon":
557
+ geometry.coordinates.forEach(processRing);
558
+ break;
559
+ case "MultiPolygon":
560
+ geometry.coordinates.forEach(
561
+ (polygon) => polygon.forEach(processRing)
562
+ );
563
+ break;
564
+ }
565
+ if (minLng === Infinity) return null;
566
+ return [
567
+ [minLng, minLat],
568
+ [maxLng, maxLat]
569
+ ];
570
+ }
571
+ function boundsIntersect(a, b) {
572
+ return !(a[1][0] < b[0][0] || // a is left of b
573
+ a[0][0] > b[1][0] || // a is right of b
574
+ a[1][1] < b[0][1] || // a is below b
575
+ a[0][1] > b[1][1]);
576
+ }
577
+ function normalizeBounds(bounds) {
578
+ if (Array.isArray(bounds) && Array.isArray(bounds[0])) {
579
+ return bounds;
580
+ }
581
+ const mapBounds = bounds;
582
+ return [mapBounds.southwest, mapBounds.northeast];
583
+ }
584
+ function queryByBoundsWithStats(index, queryBounds, options = {}) {
585
+ const { buffer = 0.01, bufferFraction } = options;
586
+ if (index.featureCount === 0) {
587
+ return {
588
+ data: { type: "FeatureCollection", features: [] },
589
+ stats: {
590
+ totalFeatures: 0,
591
+ visibleFeatures: 0,
592
+ culledPercent: 0,
593
+ cellsChecked: 0,
594
+ totalCells: 0
595
+ }
596
+ };
597
+ }
598
+ let [[minLng, minLat], [maxLng, maxLat]] = normalizeBounds(queryBounds);
599
+ const viewWidth = maxLng - minLng;
600
+ const viewHeight = maxLat - minLat;
601
+ const actualBuffer = bufferFraction ? Math.max(viewWidth, viewHeight) * bufferFraction : buffer;
602
+ minLng -= actualBuffer;
603
+ minLat -= actualBuffer;
604
+ maxLng += actualBuffer;
605
+ maxLat += actualBuffer;
606
+ const [[idxMinLng, idxMinLat]] = index.bounds;
607
+ const minCol = Math.max(0, Math.floor((minLng - idxMinLng) / index.cellWidth));
608
+ const maxCol = Math.min(index.cols - 1, Math.floor((maxLng - idxMinLng) / index.cellWidth));
609
+ const minRow = Math.max(0, Math.floor((minLat - idxMinLat) / index.cellHeight));
610
+ const maxRow = Math.min(index.rows - 1, Math.floor((maxLat - idxMinLat) / index.cellHeight));
611
+ const seen = /* @__PURE__ */ new Set();
612
+ const features = [];
613
+ let cellsChecked = 0;
614
+ for (let col = minCol; col <= maxCol; col++) {
615
+ for (let row = minRow; row <= maxRow; row++) {
616
+ cellsChecked++;
617
+ const cell = index.grid.get(`${col},${row}`);
618
+ if (cell) {
619
+ for (const feature of cell.features) {
620
+ if (!seen.has(feature)) {
621
+ const featureBounds = getFeatureBounds(feature);
622
+ if (featureBounds && boundsIntersect(featureBounds, [
623
+ [minLng, minLat],
624
+ [maxLng, maxLat]
625
+ ])) {
626
+ seen.add(feature);
627
+ features.push(feature);
628
+ }
629
+ }
630
+ }
631
+ }
632
+ }
633
+ }
634
+ const visibleFeatures = features.length;
635
+ const culledPercent = index.featureCount > 0 ? (index.featureCount - visibleFeatures) / index.featureCount * 100 : 0;
636
+ return {
637
+ data: { type: "FeatureCollection", features },
638
+ stats: {
639
+ totalFeatures: index.featureCount,
640
+ visibleFeatures,
641
+ culledPercent,
642
+ cellsChecked,
643
+ totalCells: index.cols * index.rows
644
+ }
645
+ };
646
+ }
647
+ function buildRTreeIndex(geojson, options = {}) {
648
+ const { maxEntries = 9 } = options;
649
+ const tree = new RBush(maxEntries);
650
+ const items = [];
651
+ let minLngAll = Infinity;
652
+ let minLatAll = Infinity;
653
+ let maxLngAll = -Infinity;
654
+ let maxLatAll = -Infinity;
655
+ for (const feature of geojson.features) {
656
+ const featureBounds = getFeatureBoundsInternal(feature);
657
+ if (!featureBounds) continue;
658
+ const [[minLng, minLat], [maxLng, maxLat]] = featureBounds;
659
+ items.push({
660
+ minX: minLng,
661
+ minY: minLat,
662
+ maxX: maxLng,
663
+ maxY: maxLat,
664
+ feature
665
+ });
666
+ minLngAll = Math.min(minLngAll, minLng);
667
+ minLatAll = Math.min(minLatAll, minLat);
668
+ maxLngAll = Math.max(maxLngAll, maxLng);
669
+ maxLatAll = Math.max(maxLatAll, maxLat);
670
+ }
671
+ tree.load(items);
672
+ const bounds = minLngAll === Infinity ? [
673
+ [0, 0],
674
+ [0, 0]
675
+ ] : [
676
+ [minLngAll, minLatAll],
677
+ [maxLngAll, maxLatAll]
678
+ ];
679
+ return {
680
+ tree,
681
+ bounds,
682
+ featureCount: items.length
683
+ };
684
+ }
685
+ function getFeatureBoundsInternal(feature) {
686
+ const geometry = feature.geometry;
687
+ if (!geometry) return null;
688
+ let minLng = Infinity;
689
+ let minLat = Infinity;
690
+ let maxLng = -Infinity;
691
+ let maxLat = -Infinity;
692
+ function processCoord(coord) {
693
+ minLng = Math.min(minLng, coord[0]);
694
+ minLat = Math.min(minLat, coord[1]);
695
+ maxLng = Math.max(maxLng, coord[0]);
696
+ maxLat = Math.max(maxLat, coord[1]);
697
+ }
698
+ function processRing(ring) {
699
+ ring.forEach(processCoord);
700
+ }
701
+ switch (geometry.type) {
702
+ case "Point":
703
+ processCoord(geometry.coordinates);
704
+ break;
705
+ case "MultiPoint":
706
+ case "LineString":
707
+ geometry.coordinates.forEach(processCoord);
708
+ break;
709
+ case "MultiLineString":
710
+ case "Polygon":
711
+ geometry.coordinates.forEach(processRing);
712
+ break;
713
+ case "MultiPolygon":
714
+ geometry.coordinates.forEach(
715
+ (polygon) => polygon.forEach(processRing)
716
+ );
717
+ break;
718
+ }
719
+ if (minLng === Infinity) return null;
720
+ return [
721
+ [minLng, minLat],
722
+ [maxLng, maxLat]
723
+ ];
724
+ }
725
+ function queryRTreeByBoundsWithStats(index, queryBounds, options = {}) {
726
+ const { buffer = 0.01, bufferFraction } = options;
727
+ if (index.featureCount === 0) {
728
+ return {
729
+ data: { type: "FeatureCollection", features: [] },
730
+ stats: {
731
+ totalFeatures: 0,
732
+ visibleFeatures: 0,
733
+ culledPercent: 0,
734
+ queryTimeMs: 0
735
+ }
736
+ };
737
+ }
738
+ const startTime = performance.now();
739
+ let [[minLng, minLat], [maxLng, maxLat]] = normalizeBoundsInternal(queryBounds);
740
+ const viewWidth = maxLng - minLng;
741
+ const viewHeight = maxLat - minLat;
742
+ const actualBuffer = bufferFraction ? Math.max(viewWidth, viewHeight) * bufferFraction : buffer;
743
+ minLng -= actualBuffer;
744
+ minLat -= actualBuffer;
745
+ maxLng += actualBuffer;
746
+ maxLat += actualBuffer;
747
+ const results = index.tree.search({
748
+ minX: minLng,
749
+ minY: minLat,
750
+ maxX: maxLng,
751
+ maxY: maxLat
752
+ });
753
+ const queryTimeMs = performance.now() - startTime;
754
+ const visibleFeatures = results.length;
755
+ const culledPercent = index.featureCount > 0 ? (index.featureCount - visibleFeatures) / index.featureCount * 100 : 0;
756
+ return {
757
+ data: {
758
+ type: "FeatureCollection",
759
+ features: results.map((item) => item.feature)
760
+ },
761
+ stats: {
762
+ totalFeatures: index.featureCount,
763
+ visibleFeatures,
764
+ culledPercent,
765
+ queryTimeMs
766
+ }
767
+ };
768
+ }
769
+ function normalizeBoundsInternal(bounds) {
770
+ if (Array.isArray(bounds) && Array.isArray(bounds[0])) {
771
+ return bounds;
772
+ }
773
+ const mapBounds = bounds;
774
+ return [mapBounds.southwest, mapBounds.northeast];
775
+ }
776
+
777
+ // src/workers/spatial.worker.ts
778
+ var state = {
779
+ initialized: false,
780
+ indexType: "rtree",
781
+ gridIndex: null,
782
+ rtreeIndex: null,
783
+ bounds: null,
784
+ featureCount: 0,
785
+ predictive: {
786
+ lastBounds: null,
787
+ lastData: null,
788
+ lastStats: null,
789
+ viewportSamples: [],
790
+ velocity: { lngPerSec: 0, latPerSec: 0, magnitude: 0 }
791
+ }
792
+ };
793
+ function sendResponse(response) {
794
+ self.postMessage(response);
795
+ }
796
+ function calculatePanVelocity(samples) {
797
+ if (samples.length < 2) {
798
+ return { lngPerSec: 0, latPerSec: 0, magnitude: 0 };
799
+ }
800
+ let totalLngDelta = 0;
801
+ let totalLatDelta = 0;
802
+ let totalTime = 0;
803
+ let weight = 1;
804
+ for (let i = samples.length - 1; i > 0; i--) {
805
+ const current = samples[i];
806
+ const previous = samples[i - 1];
807
+ const dt = (current.timestamp - previous.timestamp) / 1e3;
808
+ if (dt > 0 && dt < 1) {
809
+ totalLngDelta += (current.center[0] - previous.center[0]) * weight;
810
+ totalLatDelta += (current.center[1] - previous.center[1]) * weight;
811
+ totalTime += dt * weight;
812
+ }
813
+ weight *= 0.7;
814
+ }
815
+ if (totalTime === 0) {
816
+ return { lngPerSec: 0, latPerSec: 0, magnitude: 0 };
817
+ }
818
+ const lngPerSec = totalLngDelta / totalTime;
819
+ const latPerSec = totalLatDelta / totalTime;
820
+ const magnitude = Math.sqrt(lngPerSec * lngPerSec + latPerSec * latPerSec);
821
+ return { lngPerSec, latPerSec, magnitude };
822
+ }
823
+ function applyPredictiveBuffer(bounds, velocity, baseBuffer, multiplier) {
824
+ const [[minLng, minLat], [maxLng, maxLat]] = bounds;
825
+ let bufferMinLng = baseBuffer;
826
+ let bufferMaxLng = baseBuffer;
827
+ let bufferMinLat = baseBuffer;
828
+ let bufferMaxLat = baseBuffer;
829
+ if (velocity.magnitude > 1e-5) {
830
+ const extraBuffer = baseBuffer * (multiplier - 1);
831
+ if (velocity.lngPerSec > 0) {
832
+ bufferMaxLng += extraBuffer * Math.min(1, velocity.lngPerSec / velocity.magnitude);
833
+ } else if (velocity.lngPerSec < 0) {
834
+ bufferMinLng += extraBuffer * Math.min(1, -velocity.lngPerSec / velocity.magnitude);
835
+ }
836
+ if (velocity.latPerSec > 0) {
837
+ bufferMaxLat += extraBuffer * Math.min(1, velocity.latPerSec / velocity.magnitude);
838
+ } else if (velocity.latPerSec < 0) {
839
+ bufferMinLat += extraBuffer * Math.min(1, -velocity.latPerSec / velocity.magnitude);
840
+ }
841
+ }
842
+ return [
843
+ [minLng - bufferMinLng, minLat - bufferMinLat],
844
+ [maxLng + bufferMaxLng, maxLat + bufferMaxLat]
845
+ ];
846
+ }
847
+ function shouldUpdatePredictive(newBounds, lastBounds, minMovement) {
848
+ if (!lastBounds) return true;
849
+ const lastWidth = lastBounds[1][0] - lastBounds[0][0];
850
+ const lastHeight = lastBounds[1][1] - lastBounds[0][1];
851
+ const movementLng = Math.abs(
852
+ (newBounds[0][0] + newBounds[1][0]) / 2 - (lastBounds[0][0] + lastBounds[1][0]) / 2
853
+ );
854
+ const movementLat = Math.abs(
855
+ (newBounds[0][1] + newBounds[1][1]) / 2 - (lastBounds[0][1] + lastBounds[1][1]) / 2
856
+ );
857
+ const movement = Math.max(movementLng / lastWidth, movementLat / lastHeight);
858
+ const newWidth = newBounds[1][0] - newBounds[0][0];
859
+ const zoomChange = Math.abs(newWidth / lastWidth - 1);
860
+ return movement > minMovement || zoomChange > 0.2;
861
+ }
862
+ function handleInitialize(requestId, data, options = {}) {
863
+ const { useRTree = true, gridTargetCells = 1024, rtreeMaxEntries = 9 } = options;
864
+ try {
865
+ const startTime = performance.now();
866
+ if (useRTree) {
867
+ state.rtreeIndex = buildRTreeIndex(data, { maxEntries: rtreeMaxEntries });
868
+ state.gridIndex = null;
869
+ state.indexType = "rtree";
870
+ state.bounds = state.rtreeIndex.bounds;
871
+ state.featureCount = state.rtreeIndex.featureCount;
872
+ } else {
873
+ state.gridIndex = buildSpatialIndex(data, { targetCells: gridTargetCells });
874
+ state.rtreeIndex = null;
875
+ state.indexType = "grid";
876
+ state.bounds = state.gridIndex.bounds;
877
+ state.featureCount = state.gridIndex.featureCount;
878
+ }
879
+ const buildTimeMs = performance.now() - startTime;
880
+ state.initialized = true;
881
+ state.predictive = {
882
+ lastBounds: null,
883
+ lastData: null,
884
+ lastStats: null,
885
+ viewportSamples: [],
886
+ velocity: { lngPerSec: 0, latPerSec: 0, magnitude: 0 }
887
+ };
888
+ const response = {
889
+ type: "initialize",
890
+ requestId,
891
+ success: true,
892
+ stats: {
893
+ featureCount: state.featureCount,
894
+ indexType: state.indexType,
895
+ buildTimeMs
896
+ }
897
+ };
898
+ sendResponse(response);
899
+ } catch (error) {
900
+ const response = {
901
+ type: "initialize",
902
+ requestId,
903
+ success: false,
904
+ error: error instanceof Error ? error.message : "Unknown error during initialization"
905
+ };
906
+ sendResponse(response);
907
+ }
908
+ }
909
+ function handleQuery(requestId, bounds, options = {}) {
910
+ if (!state.initialized) {
911
+ const response = {
912
+ type: "query",
913
+ requestId,
914
+ success: false,
915
+ error: "Worker not initialized. Call initialize first."
916
+ };
917
+ sendResponse(response);
918
+ return;
919
+ }
920
+ try {
921
+ const { bufferFraction = 0.25, buffer } = options;
922
+ const queryOptions = buffer !== void 0 ? { buffer } : { bufferFraction };
923
+ let data;
924
+ let stats;
925
+ if (state.indexType === "rtree" && state.rtreeIndex) {
926
+ const result = queryRTreeByBoundsWithStats(state.rtreeIndex, bounds, queryOptions);
927
+ data = result.data;
928
+ stats = {
929
+ totalFeatures: result.stats.totalFeatures,
930
+ visibleFeatures: result.stats.visibleFeatures,
931
+ culledPercent: result.stats.culledPercent,
932
+ cellsChecked: 0,
933
+ totalCells: 0
934
+ };
935
+ } else if (state.gridIndex) {
936
+ const result = queryByBoundsWithStats(state.gridIndex, bounds, queryOptions);
937
+ data = result.data;
938
+ stats = result.stats;
939
+ } else {
940
+ throw new Error("No index available");
941
+ }
942
+ const response = {
943
+ type: "query",
944
+ requestId,
945
+ success: true,
946
+ data,
947
+ stats
948
+ };
949
+ sendResponse(response);
950
+ } catch (error) {
951
+ const response = {
952
+ type: "query",
953
+ requestId,
954
+ success: false,
955
+ error: error instanceof Error ? error.message : "Unknown error during query"
956
+ };
957
+ sendResponse(response);
958
+ }
959
+ }
960
+ function handlePredictiveQuery(requestId, bounds, timestamp, options = {}) {
961
+ if (!state.initialized) {
962
+ const response = {
963
+ type: "predictive-query",
964
+ requestId,
965
+ success: false,
966
+ updated: false,
967
+ error: "Worker not initialized. Call initialize first."
968
+ };
969
+ sendResponse(response);
970
+ return;
971
+ }
972
+ try {
973
+ const { bufferFraction = 0.25, minMovement = 0.1, predictiveMultiplier = 2 } = options;
974
+ const center = [
975
+ (bounds[0][0] + bounds[1][0]) / 2,
976
+ (bounds[0][1] + bounds[1][1]) / 2
977
+ ];
978
+ state.predictive.viewportSamples.push({ center, timestamp });
979
+ while (state.predictive.viewportSamples.length > 5) {
980
+ state.predictive.viewportSamples.shift();
981
+ }
982
+ state.predictive.velocity = calculatePanVelocity(state.predictive.viewportSamples);
983
+ if (state.predictive.lastData && !shouldUpdatePredictive(bounds, state.predictive.lastBounds, minMovement)) {
984
+ const response2 = {
985
+ type: "predictive-query",
986
+ requestId,
987
+ success: true,
988
+ data: state.predictive.lastData,
989
+ stats: state.predictive.lastStats,
990
+ velocity: state.predictive.velocity,
991
+ updated: false
992
+ };
993
+ sendResponse(response2);
994
+ return;
995
+ }
996
+ const viewWidth = bounds[1][0] - bounds[0][0];
997
+ const viewHeight = bounds[1][1] - bounds[0][1];
998
+ const baseBuffer = Math.max(viewWidth, viewHeight) * bufferFraction;
999
+ const predictiveBounds = applyPredictiveBuffer(
1000
+ bounds,
1001
+ state.predictive.velocity,
1002
+ baseBuffer,
1003
+ predictiveMultiplier
1004
+ );
1005
+ let data;
1006
+ let stats;
1007
+ if (state.indexType === "rtree" && state.rtreeIndex) {
1008
+ const result = queryRTreeByBoundsWithStats(state.rtreeIndex, predictiveBounds, {
1009
+ buffer: 0
1010
+ });
1011
+ data = result.data;
1012
+ stats = {
1013
+ totalFeatures: result.stats.totalFeatures,
1014
+ visibleFeatures: result.stats.visibleFeatures,
1015
+ culledPercent: result.stats.culledPercent,
1016
+ cellsChecked: 0,
1017
+ totalCells: 0
1018
+ };
1019
+ } else if (state.gridIndex) {
1020
+ const result = queryByBoundsWithStats(state.gridIndex, predictiveBounds, {
1021
+ buffer: 0
1022
+ });
1023
+ data = result.data;
1024
+ stats = result.stats;
1025
+ } else {
1026
+ throw new Error("No index available");
1027
+ }
1028
+ state.predictive.lastBounds = bounds;
1029
+ state.predictive.lastData = data;
1030
+ state.predictive.lastStats = stats;
1031
+ const response = {
1032
+ type: "predictive-query",
1033
+ requestId,
1034
+ success: true,
1035
+ data,
1036
+ stats,
1037
+ velocity: state.predictive.velocity,
1038
+ updated: true
1039
+ };
1040
+ sendResponse(response);
1041
+ } catch (error) {
1042
+ const response = {
1043
+ type: "predictive-query",
1044
+ requestId,
1045
+ success: false,
1046
+ updated: false,
1047
+ error: error instanceof Error ? error.message : "Unknown error during predictive query"
1048
+ };
1049
+ sendResponse(response);
1050
+ }
1051
+ }
1052
+ function handleResetPredictive(requestId) {
1053
+ state.predictive = {
1054
+ lastBounds: null,
1055
+ lastData: null,
1056
+ lastStats: null,
1057
+ viewportSamples: [],
1058
+ velocity: { lngPerSec: 0, latPerSec: 0, magnitude: 0 }
1059
+ };
1060
+ const response = {
1061
+ type: "reset-predictive",
1062
+ requestId,
1063
+ success: true
1064
+ };
1065
+ sendResponse(response);
1066
+ }
1067
+ function handleGetStats(requestId) {
1068
+ if (!state.initialized) {
1069
+ const response2 = {
1070
+ type: "get-stats",
1071
+ requestId,
1072
+ success: false,
1073
+ error: "Worker not initialized"
1074
+ };
1075
+ sendResponse(response2);
1076
+ return;
1077
+ }
1078
+ const response = {
1079
+ type: "get-stats",
1080
+ requestId,
1081
+ success: true,
1082
+ stats: {
1083
+ featureCount: state.featureCount,
1084
+ indexType: state.indexType,
1085
+ bounds: state.bounds
1086
+ }
1087
+ };
1088
+ sendResponse(response);
1089
+ }
1090
+ function handleTerminate(requestId) {
1091
+ state.initialized = false;
1092
+ state.gridIndex = null;
1093
+ state.rtreeIndex = null;
1094
+ state.bounds = null;
1095
+ state.featureCount = 0;
1096
+ state.predictive = {
1097
+ lastBounds: null,
1098
+ lastData: null,
1099
+ lastStats: null,
1100
+ viewportSamples: [],
1101
+ velocity: { lngPerSec: 0, latPerSec: 0, magnitude: 0 }
1102
+ };
1103
+ const response = {
1104
+ type: "terminate",
1105
+ requestId,
1106
+ success: true
1107
+ };
1108
+ sendResponse(response);
1109
+ self.close();
1110
+ }
1111
+ self.onmessage = (event) => {
1112
+ const request = event.data;
1113
+ switch (request.type) {
1114
+ case "initialize":
1115
+ handleInitialize(request.requestId, request.data, request.options);
1116
+ break;
1117
+ case "query":
1118
+ handleQuery(request.requestId, request.bounds, request.options);
1119
+ break;
1120
+ case "predictive-query":
1121
+ handlePredictiveQuery(request.requestId, request.bounds, request.timestamp, request.options);
1122
+ break;
1123
+ case "reset-predictive":
1124
+ handleResetPredictive(request.requestId);
1125
+ break;
1126
+ case "get-stats":
1127
+ handleGetStats(request.requestId);
1128
+ break;
1129
+ case "terminate":
1130
+ handleTerminate(request.requestId);
1131
+ break;
1132
+ default: {
1133
+ const _exhaustive = request;
1134
+ console.error("[maps-core] Unknown worker message type:", _exhaustive);
1135
+ }
1136
+ }
1137
+ };
1138
+ self.postMessage({ type: "ready" });