@classic-homes/maps-core 0.2.8 → 0.2.10

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,2822 @@
1
+ import { lightTheme } from './chunk-ZGUACUEF.js';
2
+ import RBush from 'rbush';
3
+
4
+ // src/utils/accessibility.ts
5
+ var KEYBOARD_CONTROLS = {
6
+ pan: {
7
+ up: "Arrow Up",
8
+ down: "Arrow Down",
9
+ left: "Arrow Left",
10
+ right: "Arrow Right"
11
+ },
12
+ zoom: {
13
+ in: "Plus (+) or Equals (=)",
14
+ out: "Minus (-)"
15
+ },
16
+ rotate: {
17
+ left: "Shift + Arrow Left",
18
+ right: "Shift + Arrow Right"
19
+ },
20
+ pitch: {
21
+ increase: "Shift + Arrow Up",
22
+ decrease: "Shift + Arrow Down"
23
+ },
24
+ reset: {
25
+ bearing: "N key (reset north)",
26
+ view: "R key (reset view)"
27
+ }
28
+ };
29
+ function generateKeyboardControlsDescription() {
30
+ return `
31
+ Map keyboard controls:
32
+ Pan: Use arrow keys to move the map.
33
+ Zoom: Press plus to zoom in, minus to zoom out.
34
+ Rotate: Hold Shift and press left or right arrows.
35
+ Tilt: Hold Shift and press up or down arrows.
36
+ Press N to reset north orientation.
37
+ `.trim().replace(/\s+/g, " ");
38
+ }
39
+ function generateMapDescription(title, options) {
40
+ let description = `${title}. Interactive map`;
41
+ if (options?.center) {
42
+ const [lng, lat] = options.center;
43
+ const latDir = lat >= 0 ? "N" : "S";
44
+ const lngDir = lng >= 0 ? "E" : "W";
45
+ description += ` centered at ${Math.abs(lat).toFixed(2)} degrees ${latDir}, ${Math.abs(lng).toFixed(2)} degrees ${lngDir}`;
46
+ }
47
+ if (options?.zoom !== void 0) {
48
+ description += ` at zoom level ${options.zoom}`;
49
+ }
50
+ if (options?.featureCount !== void 0 && options.featureCount > 0) {
51
+ description += `. Contains ${options.featureCount} ${options.featureCount === 1 ? "feature" : "features"}`;
52
+ }
53
+ if (options?.markerCount !== void 0 && options.markerCount > 0) {
54
+ description += options.featureCount ? ` and ` : `. Contains `;
55
+ description += `${options.markerCount} ${options.markerCount === 1 ? "marker" : "markers"}`;
56
+ }
57
+ if (options?.layerTypes && options.layerTypes.length > 0) {
58
+ description += `. Showing ${options.layerTypes.join(", ")} layers`;
59
+ }
60
+ description += ". Use keyboard to navigate.";
61
+ return description;
62
+ }
63
+ function generateFeatureCollectionDescription(title, data) {
64
+ const featureCount = data.features.length;
65
+ if (featureCount === 0) {
66
+ return `${title}. Map layer with no features.`;
67
+ }
68
+ const geometryTypes = {};
69
+ data.features.forEach((feature) => {
70
+ const type = feature.geometry.type;
71
+ geometryTypes[type] = (geometryTypes[type] || 0) + 1;
72
+ });
73
+ const typeDescriptions = Object.entries(geometryTypes).map(([type, count]) => `${count} ${formatGeometryType(type, count)}`).join(", ");
74
+ return `${title}. Map layer with ${featureCount} features: ${typeDescriptions}.`;
75
+ }
76
+ function formatGeometryType(type, count) {
77
+ const singular = {
78
+ Point: "point",
79
+ MultiPoint: "multi-point",
80
+ LineString: "line",
81
+ MultiLineString: "multi-line",
82
+ Polygon: "polygon",
83
+ MultiPolygon: "multi-polygon"
84
+ };
85
+ const plural = {
86
+ Point: "points",
87
+ MultiPoint: "multi-points",
88
+ LineString: "lines",
89
+ MultiLineString: "multi-lines",
90
+ Polygon: "polygons",
91
+ MultiPolygon: "multi-polygons"
92
+ };
93
+ return count === 1 ? singular[type] || type.toLowerCase() : plural[type] || `${type.toLowerCase()}s`;
94
+ }
95
+ function generateMarkersDescription(title, markers) {
96
+ const count = markers.length;
97
+ if (count === 0) {
98
+ return `${title}. No markers on the map.`;
99
+ }
100
+ let description = `${title}. Map with ${count} ${count === 1 ? "marker" : "markers"}`;
101
+ const labeledMarkers = markers.filter((m) => m.label).slice(0, 3);
102
+ if (labeledMarkers.length > 0) {
103
+ const labels = labeledMarkers.map((m) => m.label).join(", ");
104
+ description += ` including ${labels}`;
105
+ if (count > labeledMarkers.length) {
106
+ description += ` and ${count - labeledMarkers.length} more`;
107
+ }
108
+ }
109
+ return description + ".";
110
+ }
111
+ function generateFeatureTable(features, propertyKeys) {
112
+ if (features.features.length === 0) {
113
+ return "";
114
+ }
115
+ const headers = ["Type", ...propertyKeys];
116
+ const headerRow = headers.map((h) => `<th scope="col">${escapeHtml(h)}</th>`).join("");
117
+ const bodyRows = features.features.slice(0, 100).map((feature) => {
118
+ const type = feature.geometry.type;
119
+ const cells = propertyKeys.map((key) => {
120
+ const value = feature.properties?.[key];
121
+ return `<td>${escapeHtml(String(value ?? ""))}</td>`;
122
+ });
123
+ return `<tr><td>${escapeHtml(type)}</td>${cells.join("")}</tr>`;
124
+ }).join("");
125
+ return `
126
+ <table class="sr-only" role="table" aria-label="Map feature data">
127
+ <thead><tr>${headerRow}</tr></thead>
128
+ <tbody>${bodyRows}</tbody>
129
+ </table>
130
+ `.trim();
131
+ }
132
+ function generateMarkerList(markers) {
133
+ if (markers.length === 0) {
134
+ return "";
135
+ }
136
+ const items = markers.slice(0, 50).map((marker) => {
137
+ const label = marker.label || "Marker";
138
+ const [lng, lat] = marker.coordinates;
139
+ return `<li>${escapeHtml(label)} at ${lat.toFixed(4)}, ${lng.toFixed(4)}</li>`;
140
+ }).join("");
141
+ return `
142
+ <ul class="sr-only" role="list" aria-label="Map markers">
143
+ ${items}
144
+ </ul>
145
+ `.trim();
146
+ }
147
+ function generateMoveAnnouncement(center, zoom, action) {
148
+ const [lng, lat] = center;
149
+ const latDir = lat >= 0 ? "north" : "south";
150
+ const lngDir = lng >= 0 ? "east" : "west";
151
+ switch (action) {
152
+ case "pan":
153
+ return `Panned to ${Math.abs(lat).toFixed(2)} ${latDir}, ${Math.abs(lng).toFixed(2)} ${lngDir}`;
154
+ case "zoom":
155
+ return `Zoom level ${zoom.toFixed(1)}`;
156
+ case "move":
157
+ default:
158
+ return `Map moved to ${Math.abs(lat).toFixed(2)} ${latDir}, ${Math.abs(lng).toFixed(2)} ${lngDir} at zoom ${zoom.toFixed(1)}`;
159
+ }
160
+ }
161
+ function escapeHtml(str) {
162
+ const htmlEntities = {
163
+ "&": "&amp;",
164
+ "<": "&lt;",
165
+ ">": "&gt;",
166
+ '"': "&quot;",
167
+ "'": "&#39;"
168
+ };
169
+ return str.replace(/[&<>"']/g, (char) => htmlEntities[char] || char);
170
+ }
171
+
172
+ // src/utils/styles.ts
173
+ function createFillStyle(options) {
174
+ const paint = {
175
+ "fill-color": options.color
176
+ };
177
+ if (options.opacity !== void 0) {
178
+ paint["fill-opacity"] = options.opacity;
179
+ }
180
+ if (options.outlineColor !== void 0) {
181
+ paint["fill-outline-color"] = options.outlineColor;
182
+ }
183
+ return { paint };
184
+ }
185
+ function createLineStyle(options) {
186
+ const paint = {
187
+ "line-color": options.color,
188
+ "line-width": options.width
189
+ };
190
+ const layout = {};
191
+ if (options.opacity !== void 0) {
192
+ paint["line-opacity"] = options.opacity;
193
+ }
194
+ if (options.dashArray) {
195
+ paint["line-dasharray"] = options.dashArray;
196
+ }
197
+ if (options.cap) {
198
+ layout["line-cap"] = options.cap;
199
+ }
200
+ if (options.join) {
201
+ layout["line-join"] = options.join;
202
+ }
203
+ return { paint, layout };
204
+ }
205
+ function createCircleStyle(options) {
206
+ const paint = {
207
+ "circle-radius": options.radius,
208
+ "circle-color": options.color
209
+ };
210
+ if (options.opacity !== void 0) {
211
+ paint["circle-opacity"] = options.opacity;
212
+ }
213
+ if (options.strokeWidth !== void 0) {
214
+ paint["circle-stroke-width"] = options.strokeWidth;
215
+ }
216
+ if (options.strokeColor !== void 0) {
217
+ paint["circle-stroke-color"] = options.strokeColor;
218
+ }
219
+ if (options.blur !== void 0) {
220
+ paint["circle-blur"] = options.blur;
221
+ }
222
+ return { paint };
223
+ }
224
+ function createExtrusionStyle(options) {
225
+ const paint = {
226
+ "fill-extrusion-height": options.height,
227
+ "fill-extrusion-color": options.color
228
+ };
229
+ if (options.baseHeight !== void 0) {
230
+ paint["fill-extrusion-base"] = options.baseHeight;
231
+ }
232
+ if (options.opacity !== void 0) {
233
+ paint["fill-extrusion-opacity"] = options.opacity;
234
+ }
235
+ if (options.verticalGradient !== void 0) {
236
+ paint["fill-extrusion-vertical-gradient"] = options.verticalGradient;
237
+ }
238
+ return { paint };
239
+ }
240
+ function createHeatmapStyle(options) {
241
+ const paint = {};
242
+ if (options.weight !== void 0) {
243
+ paint["heatmap-weight"] = options.weight;
244
+ }
245
+ if (options.intensity !== void 0) {
246
+ paint["heatmap-intensity"] = options.intensity;
247
+ }
248
+ if (options.radius !== void 0) {
249
+ paint["heatmap-radius"] = options.radius;
250
+ }
251
+ if (options.opacity !== void 0) {
252
+ paint["heatmap-opacity"] = options.opacity;
253
+ }
254
+ if (options.colorRamp) {
255
+ const stops = ["interpolate", ["linear"], ["heatmap-density"]];
256
+ options.colorRamp.forEach((color, index) => {
257
+ stops.push(index / (options.colorRamp.length - 1));
258
+ stops.push(color);
259
+ });
260
+ paint["heatmap-color"] = stops;
261
+ }
262
+ return { paint };
263
+ }
264
+ function createHoverExpression(baseValue, hoverValue, featureStateName = "hover") {
265
+ return ["case", ["boolean", ["feature-state", featureStateName], false], hoverValue, baseValue];
266
+ }
267
+ function createSelectionExpression(baseValue, selectedValue, featureStateName = "selected") {
268
+ return [
269
+ "case",
270
+ ["boolean", ["feature-state", featureStateName], false],
271
+ selectedValue,
272
+ baseValue
273
+ ];
274
+ }
275
+ function createInteractiveExpression(baseValue, hoverValue, selectedValue) {
276
+ return [
277
+ "case",
278
+ ["boolean", ["feature-state", "selected"], false],
279
+ selectedValue,
280
+ ["boolean", ["feature-state", "hover"], false],
281
+ hoverValue,
282
+ baseValue
283
+ ];
284
+ }
285
+ function createCategoricalColorExpression(property, colorMap, defaultColor) {
286
+ const expression = ["match", ["get", property]];
287
+ Object.entries(colorMap).forEach(([value, color]) => {
288
+ expression.push(value, color);
289
+ });
290
+ expression.push(defaultColor);
291
+ return expression;
292
+ }
293
+ function createContinuousColorExpression(property, stops, interpolation = "linear") {
294
+ const expression = ["interpolate"];
295
+ if (interpolation === "linear") {
296
+ expression.push(["linear"]);
297
+ } else if (interpolation === "exponential") {
298
+ expression.push(["exponential", 1]);
299
+ } else {
300
+ expression.push(interpolation);
301
+ }
302
+ expression.push(["get", property]);
303
+ stops.forEach(([value, color]) => {
304
+ expression.push(value, color);
305
+ });
306
+ return expression;
307
+ }
308
+ function createZoomExpression(stops) {
309
+ const expression = ["interpolate", ["linear"], ["zoom"]];
310
+ stops.forEach(([zoom, value]) => {
311
+ expression.push(zoom, value);
312
+ });
313
+ return expression;
314
+ }
315
+ function getHighlightStyle(theme = lightTheme) {
316
+ const { highlight, highlightSecondary } = theme.colors;
317
+ return {
318
+ fill: {
319
+ "fill-color": createHoverExpression(highlightSecondary, highlight),
320
+ "fill-opacity": createHoverExpression(0.3, 0.5),
321
+ "fill-outline-color": highlight
322
+ },
323
+ line: {
324
+ "line-color": createHoverExpression(highlightSecondary, highlight),
325
+ "line-width": createHoverExpression(2, 3)
326
+ },
327
+ circle: {
328
+ "circle-color": createHoverExpression(highlightSecondary, highlight),
329
+ "circle-radius": createHoverExpression(6, 8),
330
+ "circle-stroke-color": highlight,
331
+ "circle-stroke-width": 2
332
+ }
333
+ };
334
+ }
335
+ function getSelectionStyle(theme = lightTheme) {
336
+ const { selection, highlight } = theme.colors;
337
+ return {
338
+ fill: {
339
+ "fill-color": createInteractiveExpression(highlight, highlight, selection),
340
+ "fill-opacity": createInteractiveExpression(0.2, 0.4, 0.6),
341
+ "fill-outline-color": createInteractiveExpression(highlight, highlight, selection)
342
+ },
343
+ line: {
344
+ "line-color": createInteractiveExpression(highlight, highlight, selection),
345
+ "line-width": createInteractiveExpression(2, 3, 4)
346
+ },
347
+ circle: {
348
+ "circle-color": createInteractiveExpression(highlight, highlight, selection),
349
+ "circle-radius": createInteractiveExpression(6, 8, 10),
350
+ "circle-stroke-color": createInteractiveExpression(highlight, highlight, selection),
351
+ "circle-stroke-width": 2
352
+ }
353
+ };
354
+ }
355
+ function createLotFillStyle(options) {
356
+ const { defaultColor, hoverColor, selectedColor, opacity = 0.7 } = options;
357
+ const fillColor = selectedColor ? createInteractiveExpression(defaultColor, hoverColor, selectedColor) : createHoverExpression(defaultColor, hoverColor);
358
+ return {
359
+ "fill-color": fillColor,
360
+ "fill-opacity": opacity
361
+ };
362
+ }
363
+ function createLotOutlineStyle(options) {
364
+ const {
365
+ defaultColor,
366
+ hoverColor,
367
+ selectedColor,
368
+ defaultWidth = 1,
369
+ hoverWidth = 2,
370
+ selectedWidth = 3
371
+ } = options;
372
+ const lineColor = selectedColor ? createInteractiveExpression(defaultColor, hoverColor, selectedColor) : createHoverExpression(defaultColor, hoverColor);
373
+ const lineWidth = selectedColor ? createInteractiveExpression(defaultWidth, hoverWidth, selectedWidth) : createHoverExpression(defaultWidth, hoverWidth);
374
+ return {
375
+ "line-color": lineColor,
376
+ "line-width": lineWidth
377
+ };
378
+ }
379
+ function createExtrusionHeightExpression(property, options = {}) {
380
+ const { scale = 1, minHeight = 0, maxHeight, defaultHeight = 0 } = options;
381
+ let heightExpr = ["coalesce", ["get", property], defaultHeight];
382
+ if (scale !== 1) {
383
+ heightExpr = ["*", heightExpr, scale];
384
+ }
385
+ if (minHeight > 0) {
386
+ heightExpr = ["max", heightExpr, minHeight];
387
+ }
388
+ if (maxHeight !== void 0) {
389
+ heightExpr = ["min", heightExpr, maxHeight];
390
+ }
391
+ return heightExpr;
392
+ }
393
+ function createStatusColorExpression(statusColors, defaultColor = "#888888") {
394
+ return createCategoricalColorExpression("status", statusColors, defaultColor);
395
+ }
396
+ function createInteractiveStatusColorExpression(statusColors, options) {
397
+ const { hoverColor, selectedColor, defaultColor = "#888888" } = options;
398
+ const baseExpr = createCategoricalColorExpression("status", statusColors, defaultColor);
399
+ if (selectedColor) {
400
+ return [
401
+ "case",
402
+ ["boolean", ["feature-state", "selected"], false],
403
+ selectedColor,
404
+ ["boolean", ["feature-state", "hover"], false],
405
+ hoverColor,
406
+ baseExpr
407
+ ];
408
+ }
409
+ return ["case", ["boolean", ["feature-state", "hover"], false], hoverColor, baseExpr];
410
+ }
411
+
412
+ // src/utils/format.ts
413
+ function formatCoordinates(coordinates, precision = 6, format = "decimal") {
414
+ const [lng, lat] = coordinates;
415
+ switch (format) {
416
+ case "dms":
417
+ return `${decimalToDMS(lat, "lat")}, ${decimalToDMS(lng, "lng")}`;
418
+ case "dd":
419
+ return `${lat.toFixed(precision)}, ${lng.toFixed(precision)}`;
420
+ case "decimal":
421
+ default:
422
+ return `${lng.toFixed(precision)}, ${lat.toFixed(precision)}`;
423
+ }
424
+ }
425
+ function decimalToDMS(decimal, type) {
426
+ const absolute = Math.abs(decimal);
427
+ const degrees = Math.floor(absolute);
428
+ const minutesDecimal = (absolute - degrees) * 60;
429
+ const minutes = Math.floor(minutesDecimal);
430
+ const seconds = ((minutesDecimal - minutes) * 60).toFixed(1);
431
+ let direction;
432
+ if (type === "lat") {
433
+ direction = decimal >= 0 ? "N" : "S";
434
+ } else {
435
+ direction = decimal >= 0 ? "E" : "W";
436
+ }
437
+ return `${degrees}\xB0 ${minutes}' ${seconds}" ${direction}`;
438
+ }
439
+ function formatDistance(meters, unit = "metric") {
440
+ if (unit === "imperial") {
441
+ const feet = meters * 3.28084;
442
+ if (feet < 1e3) {
443
+ return `${Math.round(feet)} ft`;
444
+ }
445
+ const miles = feet / 5280;
446
+ if (miles < 10) {
447
+ return `${miles.toFixed(1)} mi`;
448
+ }
449
+ return `${Math.round(miles)} mi`;
450
+ }
451
+ if (meters < 1e3) {
452
+ return `${Math.round(meters)} m`;
453
+ }
454
+ const km = meters / 1e3;
455
+ if (km < 10) {
456
+ return `${km.toFixed(1)} km`;
457
+ }
458
+ return `${Math.round(km)} km`;
459
+ }
460
+ function formatArea(sqMeters, unit = "metric") {
461
+ if (unit === "imperial") {
462
+ const sqFeet = sqMeters * 10.7639;
463
+ if (sqFeet < 43560) {
464
+ return `${Math.round(sqFeet).toLocaleString()} sq ft`;
465
+ }
466
+ const acres = sqFeet / 43560;
467
+ if (acres < 640) {
468
+ return `${acres.toFixed(2)} acres`;
469
+ }
470
+ const sqMiles = acres / 640;
471
+ return `${sqMiles.toFixed(2)} sq mi`;
472
+ }
473
+ if (sqMeters < 1e4) {
474
+ return `${Math.round(sqMeters).toLocaleString()} m\xB2`;
475
+ }
476
+ const hectares = sqMeters / 1e4;
477
+ if (hectares < 100) {
478
+ return `${hectares.toFixed(2)} ha`;
479
+ }
480
+ const sqKm = sqMeters / 1e6;
481
+ return `${sqKm.toFixed(2)} km\xB2`;
482
+ }
483
+ function formatBounds(bounds) {
484
+ let sw;
485
+ let ne;
486
+ if (Array.isArray(bounds) && Array.isArray(bounds[0])) {
487
+ const arr = bounds;
488
+ sw = arr[0];
489
+ ne = arr[1];
490
+ } else {
491
+ const b = bounds;
492
+ sw = b.southwest;
493
+ ne = b.northeast;
494
+ }
495
+ return `SW: ${formatCoordinates(sw, 4)}, NE: ${formatCoordinates(ne, 4)}`;
496
+ }
497
+ function formatZoom(zoom) {
498
+ return `Zoom: ${zoom.toFixed(1)}`;
499
+ }
500
+ function formatBearing(bearing) {
501
+ const normalized = (bearing % 360 + 360) % 360;
502
+ let direction;
503
+ if (normalized >= 337.5 || normalized < 22.5) {
504
+ direction = "N";
505
+ } else if (normalized >= 22.5 && normalized < 67.5) {
506
+ direction = "NE";
507
+ } else if (normalized >= 67.5 && normalized < 112.5) {
508
+ direction = "E";
509
+ } else if (normalized >= 112.5 && normalized < 157.5) {
510
+ direction = "SE";
511
+ } else if (normalized >= 157.5 && normalized < 202.5) {
512
+ direction = "S";
513
+ } else if (normalized >= 202.5 && normalized < 247.5) {
514
+ direction = "SW";
515
+ } else if (normalized >= 247.5 && normalized < 292.5) {
516
+ direction = "W";
517
+ } else {
518
+ direction = "NW";
519
+ }
520
+ return `${Math.round(normalized)}\xB0 ${direction}`;
521
+ }
522
+ function formatPitch(pitch) {
523
+ return `${Math.round(pitch)}\xB0 tilt`;
524
+ }
525
+ function formatScale(scale) {
526
+ if (scale >= 1e6) {
527
+ return `1:${(scale / 1e6).toFixed(1)}M`;
528
+ }
529
+ if (scale >= 1e3) {
530
+ return `1:${Math.round(scale / 1e3)}K`;
531
+ }
532
+ return `1:${Math.round(scale)}`;
533
+ }
534
+ function zoomToScale(zoom, latitude = 0) {
535
+ const metersPerPixel = 40075e3 * Math.cos(latitude * Math.PI / 180) / (256 * Math.pow(2, zoom));
536
+ const screenMetersPerPixel = 264583e-9;
537
+ return Math.round(metersPerPixel / screenMetersPerPixel);
538
+ }
539
+ function formatPropertyValue(value) {
540
+ if (value === null || value === void 0) {
541
+ return "-";
542
+ }
543
+ if (typeof value === "number") {
544
+ if (Math.abs(value) <= 180 && value !== Math.floor(value)) {
545
+ return value.toFixed(6);
546
+ }
547
+ if (Math.abs(value) >= 1e3) {
548
+ return value.toLocaleString();
549
+ }
550
+ if (value !== Math.floor(value)) {
551
+ return value.toFixed(2);
552
+ }
553
+ return String(value);
554
+ }
555
+ if (typeof value === "boolean") {
556
+ return value ? "Yes" : "No";
557
+ }
558
+ if (Array.isArray(value)) {
559
+ return value.map(formatPropertyValue).join(", ");
560
+ }
561
+ if (typeof value === "object") {
562
+ return JSON.stringify(value);
563
+ }
564
+ return String(value);
565
+ }
566
+ function formatFeatureProperties(properties, options) {
567
+ const exclude = options?.exclude || ["id", "_id", "fid", "ogc_fid"];
568
+ const include = options?.include;
569
+ const labelMap = options?.labelMap || {};
570
+ const entries = Object.entries(properties).filter(([key]) => {
571
+ if (include) {
572
+ return include.includes(key);
573
+ }
574
+ return !exclude.includes(key) && !key.startsWith("_");
575
+ }).map(([key, value]) => {
576
+ const label = labelMap[key] || formatLabel(key);
577
+ return `<strong>${label}:</strong> ${formatPropertyValue(value)}`;
578
+ });
579
+ return entries.join("<br>");
580
+ }
581
+ function formatLabel(key) {
582
+ return key.replace(/_/g, " ").replace(/([a-z])([A-Z])/g, "$1 $2").replace(/\b\w/g, (char) => char.toUpperCase());
583
+ }
584
+ function isValidLongitude(lng) {
585
+ return typeof lng === "number" && isFinite(lng) && lng >= -180 && lng <= 180;
586
+ }
587
+ function isValidLatitude(lat) {
588
+ return typeof lat === "number" && isFinite(lat) && lat >= -90 && lat <= 90;
589
+ }
590
+ function validateCoordinates(coordinates) {
591
+ if (!Array.isArray(coordinates)) {
592
+ return { valid: false, error: "Coordinates must be an array" };
593
+ }
594
+ if (coordinates.length < 2) {
595
+ return { valid: false, error: "Coordinates must have at least 2 elements [lng, lat]" };
596
+ }
597
+ const [lng, lat] = coordinates;
598
+ if (typeof lng !== "number" || typeof lat !== "number") {
599
+ return { valid: false, error: "Longitude and latitude must be numbers" };
600
+ }
601
+ if (!isFinite(lng) || !isFinite(lat)) {
602
+ return { valid: false, error: "Coordinates must be finite numbers" };
603
+ }
604
+ if (lng < -180 || lng > 180) {
605
+ return { valid: false, error: `Longitude ${lng} out of range [-180, 180]` };
606
+ }
607
+ if (lat < -90 || lat > 90) {
608
+ return { valid: false, error: `Latitude ${lat} out of range [-90, 90]` };
609
+ }
610
+ return {
611
+ valid: true,
612
+ normalized: [lng, lat]
613
+ };
614
+ }
615
+ function ensureValidCoordinates(coordinates) {
616
+ const result = validateCoordinates(coordinates);
617
+ if (!result.valid) {
618
+ throw new Error(`Invalid coordinates: ${result.error}`);
619
+ }
620
+ return result.normalized;
621
+ }
622
+ function normalizeLongitude(lng) {
623
+ if (!isFinite(lng)) return NaN;
624
+ let normalized = lng % 360;
625
+ if (normalized > 180) {
626
+ normalized -= 360;
627
+ } else if (normalized < -180) {
628
+ normalized += 360;
629
+ }
630
+ return normalized;
631
+ }
632
+ function clampLatitude(lat) {
633
+ if (!isFinite(lat)) return NaN;
634
+ return Math.max(-90, Math.min(90, lat));
635
+ }
636
+ function validateBoundsArray(bounds) {
637
+ if (!Array.isArray(bounds)) {
638
+ return { valid: false, error: "Bounds must be an array" };
639
+ }
640
+ if (bounds.length !== 2) {
641
+ return { valid: false, error: "Bounds must have exactly 2 elements [southwest, northeast]" };
642
+ }
643
+ const swResult = validateCoordinates(bounds[0]);
644
+ if (!swResult.valid) {
645
+ return { valid: false, error: `Invalid southwest corner: ${swResult.error}` };
646
+ }
647
+ const neResult = validateCoordinates(bounds[1]);
648
+ if (!neResult.valid) {
649
+ return { valid: false, error: `Invalid northeast corner: ${neResult.error}` };
650
+ }
651
+ const [, swLat] = swResult.normalized;
652
+ const [, neLat] = neResult.normalized;
653
+ if (swLat > neLat) {
654
+ return {
655
+ valid: false,
656
+ error: `Southwest latitude (${swLat}) must be less than northeast latitude (${neLat})`
657
+ };
658
+ }
659
+ return {
660
+ valid: true,
661
+ normalized: [swResult.normalized, neResult.normalized]
662
+ };
663
+ }
664
+
665
+ // src/utils/bounds.ts
666
+ function calculateBounds(geojson) {
667
+ let minLng = Infinity;
668
+ let maxLng = -Infinity;
669
+ let minLat = Infinity;
670
+ let maxLat = -Infinity;
671
+ let hasCoordinates = false;
672
+ function processCoordinate(coord) {
673
+ const [lng, lat] = coord;
674
+ if (typeof lng === "number" && typeof lat === "number" && isFinite(lng) && isFinite(lat)) {
675
+ minLng = Math.min(minLng, lng);
676
+ maxLng = Math.max(maxLng, lng);
677
+ minLat = Math.min(minLat, lat);
678
+ maxLat = Math.max(maxLat, lat);
679
+ hasCoordinates = true;
680
+ }
681
+ }
682
+ function processGeometry(geometry) {
683
+ if (!geometry) return;
684
+ switch (geometry.type) {
685
+ case "Point":
686
+ processCoordinate(geometry.coordinates);
687
+ break;
688
+ case "MultiPoint":
689
+ case "LineString":
690
+ geometry.coordinates.forEach(processCoordinate);
691
+ break;
692
+ case "MultiLineString":
693
+ case "Polygon":
694
+ geometry.coordinates.forEach((ring) => ring.forEach(processCoordinate));
695
+ break;
696
+ case "MultiPolygon":
697
+ geometry.coordinates.forEach(
698
+ (polygon) => polygon.forEach((ring) => ring.forEach(processCoordinate))
699
+ );
700
+ break;
701
+ }
702
+ }
703
+ if (geojson.type === "FeatureCollection") {
704
+ geojson.features.forEach((feature) => processGeometry(feature.geometry));
705
+ } else if (geojson.type === "Feature") {
706
+ processGeometry(geojson.geometry);
707
+ }
708
+ if (!hasCoordinates) {
709
+ return null;
710
+ }
711
+ return [
712
+ [minLng, minLat],
713
+ // Southwest
714
+ [maxLng, maxLat]
715
+ // Northeast
716
+ ];
717
+ }
718
+ function extendBounds(bounds, point) {
719
+ const [[swLng, swLat], [neLng, neLat]] = bounds;
720
+ const [lng, lat] = point;
721
+ return [
722
+ [Math.min(swLng, lng), Math.min(swLat, lat)],
723
+ [Math.max(neLng, lng), Math.max(neLat, lat)]
724
+ ];
725
+ }
726
+ function combineBounds(bounds1, bounds2) {
727
+ const [[sw1Lng, sw1Lat], [ne1Lng, ne1Lat]] = bounds1;
728
+ const [[sw2Lng, sw2Lat], [ne2Lng, ne2Lat]] = bounds2;
729
+ return [
730
+ [Math.min(sw1Lng, sw2Lng), Math.min(sw1Lat, sw2Lat)],
731
+ [Math.max(ne1Lng, ne2Lng), Math.max(ne1Lat, ne2Lat)]
732
+ ];
733
+ }
734
+ function isValidBounds(bounds) {
735
+ if (!Array.isArray(bounds) || bounds.length !== 2) {
736
+ return false;
737
+ }
738
+ const [sw, ne] = bounds;
739
+ if (!Array.isArray(sw) || sw.length !== 2 || !Array.isArray(ne) || ne.length !== 2) {
740
+ return false;
741
+ }
742
+ const [swLng, swLat] = sw;
743
+ const [neLng, neLat] = ne;
744
+ if (typeof swLng !== "number" || typeof swLat !== "number" || typeof neLng !== "number" || typeof neLat !== "number" || !isFinite(swLng) || !isFinite(swLat) || !isFinite(neLng) || !isFinite(neLat)) {
745
+ return false;
746
+ }
747
+ if (swLat > neLat) {
748
+ return false;
749
+ }
750
+ if (swLat < -90 || swLat > 90 || neLat < -90 || neLat > 90) {
751
+ return false;
752
+ }
753
+ if (swLng < -180 || swLng > 180 || neLng < -180 || neLng > 180) {
754
+ return false;
755
+ }
756
+ return true;
757
+ }
758
+
759
+ // src/utils/data.ts
760
+ async function loadGeoJSON(url, options = {}) {
761
+ const { timeout = 3e4, fetchOptions = {}, validate = true } = options;
762
+ try {
763
+ const controller = new AbortController();
764
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
765
+ const response = await fetch(url, {
766
+ ...fetchOptions,
767
+ signal: controller.signal,
768
+ headers: {
769
+ Accept: "application/geo+json, application/json",
770
+ ...fetchOptions.headers
771
+ }
772
+ });
773
+ clearTimeout(timeoutId);
774
+ if (!response.ok) {
775
+ return {
776
+ data: null,
777
+ error: `HTTP ${response.status}: ${response.statusText}`,
778
+ success: false
779
+ };
780
+ }
781
+ const data = await response.json();
782
+ if (validate) {
783
+ const validation = validateGeoJSON(data);
784
+ if (!validation.valid) {
785
+ return {
786
+ data: null,
787
+ error: `Invalid GeoJSON: ${validation.errors.join(", ")}`,
788
+ success: false
789
+ };
790
+ }
791
+ }
792
+ return {
793
+ data,
794
+ error: null,
795
+ success: true
796
+ };
797
+ } catch (err) {
798
+ if (err instanceof Error) {
799
+ if (err.name === "AbortError") {
800
+ return {
801
+ data: null,
802
+ error: `Request timeout after ${timeout}ms`,
803
+ success: false
804
+ };
805
+ }
806
+ return {
807
+ data: null,
808
+ error: err.message,
809
+ success: false
810
+ };
811
+ }
812
+ return {
813
+ data: null,
814
+ error: "Unknown error loading GeoJSON",
815
+ success: false
816
+ };
817
+ }
818
+ }
819
+ function validateGeoJSON(data) {
820
+ const errors = [];
821
+ const geometryTypes = /* @__PURE__ */ new Set();
822
+ let featureCount = 0;
823
+ if (!data || typeof data !== "object") {
824
+ return {
825
+ valid: false,
826
+ errors: ["Data must be an object"]
827
+ };
828
+ }
829
+ const obj = data;
830
+ if (!obj.type) {
831
+ errors.push('Missing "type" property');
832
+ return { valid: false, errors };
833
+ }
834
+ if (obj.type === "FeatureCollection") {
835
+ if (!Array.isArray(obj.features)) {
836
+ errors.push('"features" must be an array');
837
+ return { valid: false, errors };
838
+ }
839
+ featureCount = obj.features.length;
840
+ for (let i = 0; i < obj.features.length; i++) {
841
+ const feature = obj.features[i];
842
+ const featureErrors = validateFeature(feature, i);
843
+ errors.push(...featureErrors.errors);
844
+ if (feature && typeof feature === "object" && feature.geometry) {
845
+ const geom = feature.geometry;
846
+ if (geom && geom.type) {
847
+ geometryTypes.add(geom.type);
848
+ }
849
+ }
850
+ }
851
+ } else if (obj.type === "Feature") {
852
+ const featureErrors = validateFeature(obj, 0);
853
+ errors.push(...featureErrors.errors);
854
+ featureCount = 1;
855
+ if (obj.geometry && typeof obj.geometry === "object") {
856
+ const geom = obj.geometry;
857
+ if (geom.type) {
858
+ geometryTypes.add(geom.type);
859
+ }
860
+ }
861
+ } else if (isGeometryType(obj.type)) {
862
+ const geomErrors = validateGeometry(obj);
863
+ errors.push(...geomErrors);
864
+ geometryTypes.add(obj.type);
865
+ } else {
866
+ errors.push(`Unknown GeoJSON type: "${obj.type}"`);
867
+ }
868
+ return {
869
+ valid: errors.length === 0,
870
+ errors,
871
+ featureCount,
872
+ geometryTypes: Array.from(geometryTypes)
873
+ };
874
+ }
875
+ function validateFeature(feature, index) {
876
+ const errors = [];
877
+ const prefix = `Feature[${index}]`;
878
+ if (!feature || typeof feature !== "object") {
879
+ errors.push(`${prefix}: must be an object`);
880
+ return { valid: false, errors };
881
+ }
882
+ const f = feature;
883
+ if (f.type !== "Feature") {
884
+ errors.push(`${prefix}: type must be "Feature"`);
885
+ }
886
+ if (f.geometry !== null && f.geometry !== void 0) {
887
+ if (typeof f.geometry !== "object") {
888
+ errors.push(`${prefix}: geometry must be an object or null`);
889
+ } else {
890
+ const geomErrors = validateGeometry(f.geometry, prefix);
891
+ errors.push(...geomErrors);
892
+ }
893
+ }
894
+ if (f.properties !== null && f.properties !== void 0) {
895
+ if (typeof f.properties !== "object") {
896
+ errors.push(`${prefix}: properties must be an object or null`);
897
+ }
898
+ }
899
+ return { valid: errors.length === 0, errors };
900
+ }
901
+ function validateGeometry(geometry, prefix = "") {
902
+ const errors = [];
903
+ const p = prefix ? `${prefix}.geometry` : "Geometry";
904
+ if (!geometry || typeof geometry !== "object") {
905
+ errors.push(`${p}: must be an object`);
906
+ return errors;
907
+ }
908
+ if (!geometry.type) {
909
+ errors.push(`${p}: missing type`);
910
+ return errors;
911
+ }
912
+ if (!isGeometryType(geometry.type)) {
913
+ errors.push(`${p}: unknown geometry type "${geometry.type}"`);
914
+ return errors;
915
+ }
916
+ if (geometry.type !== "GeometryCollection") {
917
+ if (!("coordinates" in geometry) || geometry.coordinates === void 0) {
918
+ errors.push(`${p}: missing coordinates`);
919
+ return errors;
920
+ }
921
+ if (!Array.isArray(geometry.coordinates)) {
922
+ errors.push(`${p}: coordinates must be an array`);
923
+ return errors;
924
+ }
925
+ }
926
+ switch (geometry.type) {
927
+ case "Point":
928
+ if (!isValidPosition(geometry.coordinates)) {
929
+ errors.push(`${p}: invalid Point coordinates`);
930
+ }
931
+ break;
932
+ case "MultiPoint":
933
+ case "LineString":
934
+ if (!Array.isArray(geometry.coordinates) || geometry.coordinates.length === 0) {
935
+ errors.push(`${p}: ${geometry.type} must have at least one position`);
936
+ }
937
+ break;
938
+ case "Polygon":
939
+ case "MultiLineString":
940
+ if (!Array.isArray(geometry.coordinates) || geometry.coordinates.length === 0) {
941
+ errors.push(`${p}: ${geometry.type} must have at least one ring/line`);
942
+ }
943
+ break;
944
+ case "MultiPolygon":
945
+ if (!Array.isArray(geometry.coordinates) || geometry.coordinates.length === 0) {
946
+ errors.push(`${p}: MultiPolygon must have at least one polygon`);
947
+ }
948
+ break;
949
+ case "GeometryCollection": {
950
+ const geomCollection = geometry;
951
+ if (!("geometries" in geometry)) {
952
+ errors.push(`${p}: GeometryCollection must have "geometries" array`);
953
+ } else if (!Array.isArray(geomCollection.geometries)) {
954
+ errors.push(`${p}: GeometryCollection "geometries" must be an array`);
955
+ } else {
956
+ geomCollection.geometries.forEach((geom, idx) => {
957
+ const nestedErrors = validateGeometry(geom, `${p}.geometries[${idx}]`);
958
+ errors.push(...nestedErrors);
959
+ });
960
+ }
961
+ break;
962
+ }
963
+ }
964
+ return errors;
965
+ }
966
+ function isGeometryType(type) {
967
+ return [
968
+ "Point",
969
+ "MultiPoint",
970
+ "LineString",
971
+ "MultiLineString",
972
+ "Polygon",
973
+ "MultiPolygon",
974
+ "GeometryCollection"
975
+ ].includes(type);
976
+ }
977
+ function isValidPosition(position) {
978
+ if (!Array.isArray(position)) return false;
979
+ if (position.length < 2 || position.length > 3) return false;
980
+ return position.every((coord) => typeof coord === "number" && isFinite(coord));
981
+ }
982
+ function calculateCentroid(geojson) {
983
+ const coords = [];
984
+ function collectCoordinates(geometry) {
985
+ if (!geometry) return;
986
+ switch (geometry.type) {
987
+ case "Point":
988
+ coords.push(geometry.coordinates);
989
+ break;
990
+ case "MultiPoint":
991
+ case "LineString":
992
+ geometry.coordinates.forEach((c) => coords.push(c));
993
+ break;
994
+ case "MultiLineString":
995
+ case "Polygon":
996
+ geometry.coordinates.forEach(
997
+ (ring) => ring.forEach((c) => coords.push(c))
998
+ );
999
+ break;
1000
+ case "MultiPolygon":
1001
+ geometry.coordinates.forEach(
1002
+ (polygon) => polygon.forEach((ring) => ring.forEach((c) => coords.push(c)))
1003
+ );
1004
+ break;
1005
+ }
1006
+ }
1007
+ if (geojson.type === "FeatureCollection") {
1008
+ geojson.features.forEach((f) => collectCoordinates(f.geometry));
1009
+ } else if (geojson.type === "Feature") {
1010
+ collectCoordinates(geojson.geometry);
1011
+ }
1012
+ if (coords.length === 0) return null;
1013
+ const sum = coords.reduce((acc, [lng, lat]) => [acc[0] + lng, acc[1] + lat], [0, 0]);
1014
+ return [sum[0] / coords.length, sum[1] / coords.length];
1015
+ }
1016
+ function countFeaturesByType(geojson) {
1017
+ const counts = {};
1018
+ geojson.features.forEach((feature) => {
1019
+ const type = feature.geometry?.type || "null";
1020
+ counts[type] = (counts[type] || 0) + 1;
1021
+ });
1022
+ return counts;
1023
+ }
1024
+ function filterByGeometryType(geojson, types) {
1025
+ return {
1026
+ type: "FeatureCollection",
1027
+ features: geojson.features.filter((f) => f.geometry && types.includes(f.geometry.type))
1028
+ };
1029
+ }
1030
+
1031
+ // src/utils/cluster.ts
1032
+ function isClusterFeature(feature) {
1033
+ return feature.properties !== null && feature.properties !== void 0 && typeof feature.properties === "object" && "cluster_id" in feature.properties && "point_count" in feature.properties;
1034
+ }
1035
+ async function getClusterExpansionZoom(map, sourceId, clusterId) {
1036
+ const source = map.getSource(sourceId);
1037
+ if (!source) {
1038
+ throw new Error(`Source "${sourceId}" not found`);
1039
+ }
1040
+ if (typeof source.getClusterExpansionZoom !== "function") {
1041
+ throw new Error(`Source "${sourceId}" does not support clustering`);
1042
+ }
1043
+ return source.getClusterExpansionZoom(clusterId);
1044
+ }
1045
+ async function getClusterChildren(map, sourceId, clusterId) {
1046
+ const source = map.getSource(sourceId);
1047
+ if (!source) {
1048
+ throw new Error(`Source "${sourceId}" not found`);
1049
+ }
1050
+ if (typeof source.getClusterChildren !== "function") {
1051
+ throw new Error(`Source "${sourceId}" does not support clustering`);
1052
+ }
1053
+ return source.getClusterChildren(clusterId);
1054
+ }
1055
+ async function getClusterLeaves(map, sourceId, clusterId, limit = 100, offset = 0) {
1056
+ const source = map.getSource(sourceId);
1057
+ if (!source) {
1058
+ throw new Error(`Source "${sourceId}" not found`);
1059
+ }
1060
+ if (typeof source.getClusterLeaves !== "function") {
1061
+ throw new Error(`Source "${sourceId}" does not support clustering`);
1062
+ }
1063
+ return source.getClusterLeaves(clusterId, limit, offset);
1064
+ }
1065
+ async function expandCluster(map, sourceId, clusterId, center, options = {}) {
1066
+ const { duration = 500, animate = true, padding, maxZoom } = options;
1067
+ const expansionZoom = await getClusterExpansionZoom(map, sourceId, clusterId);
1068
+ const targetZoom = maxZoom !== void 0 ? Math.min(expansionZoom, maxZoom) : expansionZoom;
1069
+ if (map.getZoom() < targetZoom) {
1070
+ map.easeTo({
1071
+ center,
1072
+ zoom: targetZoom,
1073
+ duration: animate ? duration : 0,
1074
+ animate,
1075
+ ...padding !== void 0 && { padding }
1076
+ });
1077
+ }
1078
+ }
1079
+ async function getClusterBounds(map, sourceId, clusterId, limit = 1e3) {
1080
+ const leaves = await getClusterLeaves(map, sourceId, clusterId, limit);
1081
+ if (leaves.length === 0) {
1082
+ throw new Error("Cluster has no leaves");
1083
+ }
1084
+ let minLng = Infinity;
1085
+ let minLat = Infinity;
1086
+ let maxLng = -Infinity;
1087
+ let maxLat = -Infinity;
1088
+ for (const leaf of leaves) {
1089
+ if (leaf.geometry.type === "Point") {
1090
+ const [lng, lat] = leaf.geometry.coordinates;
1091
+ minLng = Math.min(minLng, lng);
1092
+ minLat = Math.min(minLat, lat);
1093
+ maxLng = Math.max(maxLng, lng);
1094
+ maxLat = Math.max(maxLat, lat);
1095
+ }
1096
+ }
1097
+ return [
1098
+ [minLng, minLat],
1099
+ [maxLng, maxLat]
1100
+ ];
1101
+ }
1102
+ async function expandClusterToBounds(map, sourceId, clusterId, options = {}) {
1103
+ const { duration = 500, animate = true, padding = 50, maxZoom } = options;
1104
+ const bounds = await getClusterBounds(map, sourceId, clusterId);
1105
+ map.fitBounds(bounds, {
1106
+ padding,
1107
+ duration: animate ? duration : 0,
1108
+ animate,
1109
+ ...maxZoom !== void 0 && { maxZoom }
1110
+ });
1111
+ }
1112
+ function createClusterStyles(options = {}) {
1113
+ const {
1114
+ smallColor = "#51bbd6",
1115
+ mediumColor = "#f1f075",
1116
+ largeColor = "#f28cb1",
1117
+ mediumThreshold = 100,
1118
+ largeThreshold = 750,
1119
+ smallRadius = 20,
1120
+ mediumRadius = 30,
1121
+ largeRadius = 40,
1122
+ strokeColor = "#fff",
1123
+ strokeWidth = 2,
1124
+ opacity = 0.85
1125
+ } = options.circle ?? {};
1126
+ const {
1127
+ textColor = "#333",
1128
+ textSize = 12,
1129
+ fontStack = ["Open Sans Bold", "Arial Unicode MS Bold"],
1130
+ abbreviated = false
1131
+ } = options.text ?? {};
1132
+ const {
1133
+ color: pointColor = "#11b4da",
1134
+ radius: pointRadius = 8,
1135
+ strokeColor: pointStrokeColor = "#fff",
1136
+ strokeWidth: pointStrokeWidth = 1
1137
+ } = options.unclusteredPoint ?? {};
1138
+ return {
1139
+ clusterCirclePaint: {
1140
+ "circle-color": [
1141
+ "step",
1142
+ ["get", "point_count"],
1143
+ smallColor,
1144
+ mediumThreshold,
1145
+ mediumColor,
1146
+ largeThreshold,
1147
+ largeColor
1148
+ ],
1149
+ "circle-radius": [
1150
+ "step",
1151
+ ["get", "point_count"],
1152
+ smallRadius,
1153
+ mediumThreshold,
1154
+ mediumRadius,
1155
+ largeThreshold,
1156
+ largeRadius
1157
+ ],
1158
+ "circle-stroke-color": strokeColor,
1159
+ "circle-stroke-width": strokeWidth,
1160
+ "circle-opacity": opacity
1161
+ },
1162
+ clusterTextPaint: {
1163
+ "text-color": textColor
1164
+ },
1165
+ clusterTextLayout: {
1166
+ "text-field": abbreviated ? ["get", "point_count_abbreviated"] : ["to-string", ["get", "point_count"]],
1167
+ "text-font": fontStack,
1168
+ "text-size": textSize,
1169
+ "text-allow-overlap": true
1170
+ },
1171
+ unclusteredPointPaint: {
1172
+ "circle-color": pointColor,
1173
+ "circle-radius": pointRadius,
1174
+ "circle-stroke-color": pointStrokeColor,
1175
+ "circle-stroke-width": pointStrokeWidth
1176
+ },
1177
+ clusterFilter: ["has", "point_count"],
1178
+ unclusteredFilter: ["!", ["has", "point_count"]]
1179
+ };
1180
+ }
1181
+ function createClusterCirclePaint(options = {}) {
1182
+ const styles = createClusterStyles({ circle: options });
1183
+ return styles.clusterCirclePaint;
1184
+ }
1185
+ function createClusterTextLayout(options = {}) {
1186
+ const styles = createClusterStyles({ text: options });
1187
+ return styles.clusterTextLayout;
1188
+ }
1189
+
1190
+ // src/utils/lod.ts
1191
+ function groupFeaturesByProperty(geojson, options) {
1192
+ const { groupBy, subGroupBy } = options;
1193
+ const groups = /* @__PURE__ */ new Map();
1194
+ for (const feature of geojson.features) {
1195
+ const groupValue = String(feature.properties?.[groupBy] ?? "unknown");
1196
+ if (!groups.has(groupValue)) {
1197
+ groups.set(groupValue, {
1198
+ id: groupValue,
1199
+ features: [],
1200
+ bounds: null,
1201
+ centroid: null,
1202
+ count: 0,
1203
+ subGroups: subGroupBy ? /* @__PURE__ */ new Map() : void 0
1204
+ });
1205
+ }
1206
+ const group = groups.get(groupValue);
1207
+ group.features.push(feature);
1208
+ group.count++;
1209
+ if (subGroupBy && group.subGroups) {
1210
+ const subGroupValue = String(feature.properties?.[subGroupBy] ?? "unknown");
1211
+ if (!group.subGroups.has(subGroupValue)) {
1212
+ group.subGroups.set(subGroupValue, {
1213
+ id: subGroupValue,
1214
+ features: [],
1215
+ bounds: null,
1216
+ centroid: null,
1217
+ count: 0
1218
+ });
1219
+ }
1220
+ const subGroup = group.subGroups.get(subGroupValue);
1221
+ subGroup.features.push(feature);
1222
+ subGroup.count++;
1223
+ }
1224
+ }
1225
+ for (const group of groups.values()) {
1226
+ const groupCollection = {
1227
+ type: "FeatureCollection",
1228
+ features: group.features
1229
+ };
1230
+ group.bounds = calculateBounds(groupCollection);
1231
+ group.centroid = group.bounds ? calculateCentroidFromBounds(group.bounds) : null;
1232
+ if (group.subGroups) {
1233
+ for (const subGroup of group.subGroups.values()) {
1234
+ const subGroupCollection = {
1235
+ type: "FeatureCollection",
1236
+ features: subGroup.features
1237
+ };
1238
+ subGroup.bounds = calculateBounds(subGroupCollection);
1239
+ subGroup.centroid = subGroup.bounds ? calculateCentroidFromBounds(subGroup.bounds) : null;
1240
+ }
1241
+ }
1242
+ }
1243
+ return groups;
1244
+ }
1245
+ function calculateCentroidFromBounds(bounds) {
1246
+ const [[swLng, swLat], [neLng, neLat]] = bounds;
1247
+ return [(swLng + neLng) / 2, (swLat + neLat) / 2];
1248
+ }
1249
+ function generateConvexHull(features) {
1250
+ const points = [];
1251
+ for (const feature of features) {
1252
+ if (feature.geometry?.type === "Polygon") {
1253
+ const exteriorRing = feature.geometry.coordinates[0];
1254
+ points.push(...exteriorRing);
1255
+ } else if (feature.geometry?.type === "MultiPolygon") {
1256
+ for (const polygon of feature.geometry.coordinates) {
1257
+ points.push(...polygon[0]);
1258
+ }
1259
+ } else if (feature.geometry?.type === "Point") {
1260
+ points.push(feature.geometry.coordinates);
1261
+ }
1262
+ }
1263
+ if (points.length < 3) {
1264
+ return null;
1265
+ }
1266
+ const hull = convexHull(points);
1267
+ if (hull.length < 3) {
1268
+ return null;
1269
+ }
1270
+ const closedHull = [...hull, hull[0]];
1271
+ return {
1272
+ type: "Polygon",
1273
+ coordinates: [closedHull]
1274
+ };
1275
+ }
1276
+ function convexHull(points) {
1277
+ if (points.length < 3) return points;
1278
+ let leftmost = 0;
1279
+ for (let i = 1; i < points.length; i++) {
1280
+ if (points[i][0] < points[leftmost][0]) {
1281
+ leftmost = i;
1282
+ }
1283
+ }
1284
+ const hull = [];
1285
+ let current = leftmost;
1286
+ let iterations = 0;
1287
+ const maxIterations = points.length * 2;
1288
+ do {
1289
+ hull.push(points[current]);
1290
+ let next = 0;
1291
+ for (let i = 1; i < points.length; i++) {
1292
+ if (next === current || crossProduct(points[current], points[next], points[i]) < 0) {
1293
+ next = i;
1294
+ }
1295
+ }
1296
+ current = next;
1297
+ iterations++;
1298
+ } while (current !== leftmost && iterations < maxIterations);
1299
+ return hull;
1300
+ }
1301
+ function crossProduct(o, a, b) {
1302
+ return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
1303
+ }
1304
+ function generateBoundingPolygon(features, padding = 0) {
1305
+ const collection = {
1306
+ type: "FeatureCollection",
1307
+ features
1308
+ };
1309
+ const bounds = calculateBounds(collection);
1310
+ if (!bounds) return null;
1311
+ return boundsToPolygon(bounds, padding);
1312
+ }
1313
+ function boundsToPolygon(bounds, padding = 0) {
1314
+ const [[swLng, swLat], [neLng, neLat]] = bounds;
1315
+ const minLng = swLng - padding;
1316
+ const minLat = swLat - padding;
1317
+ const maxLng = neLng + padding;
1318
+ const maxLat = neLat + padding;
1319
+ return {
1320
+ type: "Polygon",
1321
+ coordinates: [
1322
+ [
1323
+ [minLng, minLat],
1324
+ // SW
1325
+ [maxLng, minLat],
1326
+ // SE
1327
+ [maxLng, maxLat],
1328
+ // NE
1329
+ [minLng, maxLat],
1330
+ // NW
1331
+ [minLng, minLat]
1332
+ // Close
1333
+ ]
1334
+ ]
1335
+ };
1336
+ }
1337
+ function perpendicularDistance(point, lineStart, lineEnd) {
1338
+ const dx = lineEnd[0] - lineStart[0];
1339
+ const dy = lineEnd[1] - lineStart[1];
1340
+ const lineLengthSquared = dx * dx + dy * dy;
1341
+ if (lineLengthSquared === 0) {
1342
+ const pdx = point[0] - lineStart[0];
1343
+ const pdy = point[1] - lineStart[1];
1344
+ return Math.sqrt(pdx * pdx + pdy * pdy);
1345
+ }
1346
+ const numerator = Math.abs(
1347
+ dy * point[0] - dx * point[1] + lineEnd[0] * lineStart[1] - lineEnd[1] * lineStart[0]
1348
+ );
1349
+ const denominator = Math.sqrt(lineLengthSquared);
1350
+ return numerator / denominator;
1351
+ }
1352
+ function douglasPeuckerSimplify(points, tolerance) {
1353
+ if (points.length <= 2) {
1354
+ return points;
1355
+ }
1356
+ let maxDistance = 0;
1357
+ let maxIndex = 0;
1358
+ const first = points[0];
1359
+ const last = points[points.length - 1];
1360
+ for (let i = 1; i < points.length - 1; i++) {
1361
+ const distance = perpendicularDistance(points[i], first, last);
1362
+ if (distance > maxDistance) {
1363
+ maxDistance = distance;
1364
+ maxIndex = i;
1365
+ }
1366
+ }
1367
+ if (maxDistance > tolerance) {
1368
+ const leftPoints = douglasPeuckerSimplify(points.slice(0, maxIndex + 1), tolerance);
1369
+ const rightPoints = douglasPeuckerSimplify(points.slice(maxIndex), tolerance);
1370
+ return leftPoints.slice(0, -1).concat(rightPoints);
1371
+ } else {
1372
+ return [first, last];
1373
+ }
1374
+ }
1375
+ function simplifyRing(ring, tolerance) {
1376
+ if (ring.length < 4) {
1377
+ return ring;
1378
+ }
1379
+ const openRing = ring.slice(0, -1);
1380
+ const simplified = douglasPeuckerSimplify(openRing, tolerance);
1381
+ if (simplified.length < 3) {
1382
+ return ring;
1383
+ }
1384
+ return [...simplified, simplified[0]];
1385
+ }
1386
+ function simplifyPolygon(polygon, tolerance) {
1387
+ const simplifiedCoords = polygon.coordinates.map((ring) => simplifyRing(ring, tolerance));
1388
+ return {
1389
+ type: "Polygon",
1390
+ coordinates: simplifiedCoords
1391
+ };
1392
+ }
1393
+ function simplifyFeature(feature, tolerance) {
1394
+ if (!feature.geometry) {
1395
+ return feature;
1396
+ }
1397
+ switch (feature.geometry.type) {
1398
+ case "Point":
1399
+ case "MultiPoint":
1400
+ case "LineString":
1401
+ case "MultiLineString":
1402
+ return feature;
1403
+ case "Polygon":
1404
+ return {
1405
+ ...feature,
1406
+ geometry: simplifyPolygon(feature.geometry, tolerance)
1407
+ };
1408
+ case "MultiPolygon": {
1409
+ const multiPolygon = feature.geometry;
1410
+ const simplifiedPolygons = multiPolygon.coordinates.map((polygonCoords) => {
1411
+ return polygonCoords.map((ring) => simplifyRing(ring, tolerance));
1412
+ });
1413
+ return {
1414
+ ...feature,
1415
+ geometry: {
1416
+ type: "MultiPolygon",
1417
+ coordinates: simplifiedPolygons
1418
+ }
1419
+ };
1420
+ }
1421
+ default:
1422
+ return feature;
1423
+ }
1424
+ }
1425
+ function simplifyFeatureCollection(collection, tolerance) {
1426
+ return {
1427
+ type: "FeatureCollection",
1428
+ features: collection.features.map((f) => simplifyFeature(f, tolerance))
1429
+ };
1430
+ }
1431
+ function countVertices(collection) {
1432
+ let count = 0;
1433
+ for (const feature of collection.features) {
1434
+ if (!feature.geometry) continue;
1435
+ switch (feature.geometry.type) {
1436
+ case "Point":
1437
+ count += 1;
1438
+ break;
1439
+ case "MultiPoint":
1440
+ case "LineString":
1441
+ count += feature.geometry.coordinates.length;
1442
+ break;
1443
+ case "MultiLineString":
1444
+ case "Polygon":
1445
+ for (const ring of feature.geometry.coordinates) {
1446
+ count += ring.length;
1447
+ }
1448
+ break;
1449
+ case "MultiPolygon":
1450
+ for (const polygon of feature.geometry.coordinates) {
1451
+ for (const ring of polygon) {
1452
+ count += ring.length;
1453
+ }
1454
+ }
1455
+ break;
1456
+ }
1457
+ }
1458
+ return count;
1459
+ }
1460
+ function simplifyFeatureCollectionWithStats(collection, tolerance) {
1461
+ const originalVertices = countVertices(collection);
1462
+ const simplified = simplifyFeatureCollection(collection, tolerance);
1463
+ const simplifiedVertices = countVertices(simplified);
1464
+ const reductionPercent = originalVertices > 0 ? (originalVertices - simplifiedVertices) / originalVertices * 100 : 0;
1465
+ return {
1466
+ data: simplified,
1467
+ stats: {
1468
+ originalVertices,
1469
+ simplifiedVertices,
1470
+ reductionPercent,
1471
+ featureCount: collection.features.length
1472
+ }
1473
+ };
1474
+ }
1475
+ function generateLODData(geojson, options) {
1476
+ const {
1477
+ groupBy,
1478
+ subGroupBy,
1479
+ groupBoundaries: providedGroupBoundaries,
1480
+ subGroupBoundaries: providedSubGroupBoundaries,
1481
+ useConvexHull = true,
1482
+ boundaryPadding = 1e-4,
1483
+ aggregateProperties = []
1484
+ } = options;
1485
+ const groups = groupFeaturesByProperty(geojson, { groupBy, subGroupBy });
1486
+ const groupBoundaryFeatures = [];
1487
+ for (const [groupId, group] of groups) {
1488
+ let geometry = providedGroupBoundaries?.get(groupId) ?? null;
1489
+ if (!geometry) {
1490
+ geometry = useConvexHull ? generateConvexHull(group.features) : generateBoundingPolygon(group.features, boundaryPadding);
1491
+ }
1492
+ if (geometry) {
1493
+ const aggregated = {};
1494
+ for (const prop of aggregateProperties) {
1495
+ const values = group.features.map((f) => f.properties?.[prop]).filter((v) => v !== void 0);
1496
+ if (values.length > 0) {
1497
+ if (typeof values[0] === "number") {
1498
+ aggregated[prop] = values.reduce((a, b) => a + b, 0);
1499
+ } else {
1500
+ aggregated[`${prop}Count`] = new Set(values).size;
1501
+ }
1502
+ }
1503
+ }
1504
+ groupBoundaryFeatures.push({
1505
+ type: "Feature",
1506
+ properties: {
1507
+ [groupBy]: groupId,
1508
+ lotCount: group.count,
1509
+ ...aggregated
1510
+ },
1511
+ geometry
1512
+ });
1513
+ }
1514
+ }
1515
+ let subGroupBoundaryFeatures = null;
1516
+ if (subGroupBy) {
1517
+ subGroupBoundaryFeatures = [];
1518
+ for (const [groupId, group] of groups) {
1519
+ if (group.subGroups) {
1520
+ for (const [subGroupId, subGroup] of group.subGroups) {
1521
+ const boundaryKey = `${groupId}:${subGroupId}`;
1522
+ let geometry = providedSubGroupBoundaries?.get(boundaryKey) ?? null;
1523
+ if (!geometry) {
1524
+ geometry = useConvexHull ? generateConvexHull(subGroup.features) : generateBoundingPolygon(subGroup.features, boundaryPadding);
1525
+ }
1526
+ if (geometry) {
1527
+ const aggregated = {};
1528
+ for (const prop of aggregateProperties) {
1529
+ const values = subGroup.features.map((f) => f.properties?.[prop]).filter((v) => v !== void 0);
1530
+ if (values.length > 0) {
1531
+ if (typeof values[0] === "number") {
1532
+ aggregated[prop] = values.reduce((a, b) => a + b, 0);
1533
+ } else {
1534
+ aggregated[`${prop}Count`] = new Set(values).size;
1535
+ }
1536
+ }
1537
+ }
1538
+ subGroupBoundaryFeatures.push({
1539
+ type: "Feature",
1540
+ properties: {
1541
+ [groupBy]: groupId,
1542
+ [subGroupBy]: subGroupId,
1543
+ lotCount: subGroup.count,
1544
+ ...aggregated
1545
+ },
1546
+ geometry
1547
+ });
1548
+ }
1549
+ }
1550
+ }
1551
+ }
1552
+ }
1553
+ return {
1554
+ groupBoundaries: {
1555
+ type: "FeatureCollection",
1556
+ features: groupBoundaryFeatures
1557
+ },
1558
+ subGroupBoundaries: subGroupBoundaryFeatures ? {
1559
+ type: "FeatureCollection",
1560
+ features: subGroupBoundaryFeatures
1561
+ } : null,
1562
+ features: geojson,
1563
+ zoomThresholds: {
1564
+ groupMaxZoom: 12,
1565
+ subGroupMaxZoom: 14
1566
+ }
1567
+ };
1568
+ }
1569
+ function generateLODDataWithSimplification(geojson, options) {
1570
+ const baseLOD = generateLODData(geojson, options);
1571
+ const { simplificationThresholds } = options;
1572
+ if (!simplificationThresholds || simplificationThresholds.length === 0) {
1573
+ return baseLOD;
1574
+ }
1575
+ const sortedThresholds = [...simplificationThresholds].sort((a, b) => b.maxZoom - a.maxZoom);
1576
+ const simplifiedFeatures = /* @__PURE__ */ new Map();
1577
+ const simplificationStats = /* @__PURE__ */ new Map();
1578
+ for (const threshold of sortedThresholds) {
1579
+ const { data, stats } = simplifyFeatureCollectionWithStats(geojson, threshold.tolerance);
1580
+ simplifiedFeatures.set(threshold.maxZoom, data);
1581
+ simplificationStats.set(threshold.maxZoom, stats);
1582
+ }
1583
+ return {
1584
+ ...baseLOD,
1585
+ simplifiedFeatures,
1586
+ simplificationStats
1587
+ };
1588
+ }
1589
+ function getSimplifiedFeaturesForZoom(lodData, zoom) {
1590
+ if (!lodData.simplifiedFeatures || lodData.simplifiedFeatures.size === 0) {
1591
+ return lodData.features;
1592
+ }
1593
+ let bestMatch = null;
1594
+ for (const [maxZoom, features] of lodData.simplifiedFeatures) {
1595
+ if (zoom < maxZoom) {
1596
+ if (!bestMatch) {
1597
+ bestMatch = features;
1598
+ }
1599
+ }
1600
+ }
1601
+ return bestMatch ?? lodData.features;
1602
+ }
1603
+ function calculateZoomThresholds(groups, options = {}) {
1604
+ const { minZoomGap = 2 } = options;
1605
+ const groupCount = groups.size;
1606
+ let subGroupCount = 0;
1607
+ for (const group of groups.values()) {
1608
+ if (group.subGroups) {
1609
+ subGroupCount += group.subGroups.size;
1610
+ }
1611
+ }
1612
+ const groupMaxZoom = Math.max(10, Math.min(14, 10 + Math.log2(groupCount)));
1613
+ const subGroupMaxZoom = Math.max(
1614
+ groupMaxZoom + minZoomGap,
1615
+ Math.min(16, groupMaxZoom + Math.log2(Math.max(1, subGroupCount / groupCount)))
1616
+ );
1617
+ return {
1618
+ groupMaxZoom: Math.round(groupMaxZoom),
1619
+ subGroupMaxZoom: Math.round(subGroupMaxZoom)
1620
+ };
1621
+ }
1622
+ function createDynamicLODManager(options) {
1623
+ const {
1624
+ baseThresholds,
1625
+ targetFps = 50,
1626
+ adjustBelowFps = 40,
1627
+ maxAdjustment = 3,
1628
+ adjustmentStep = 0.5,
1629
+ smoothingFactor = 0.3,
1630
+ adjustmentCooldown = 1e3
1631
+ } = options;
1632
+ let averageFps = targetFps;
1633
+ let adjustment = 0;
1634
+ let lastAdjustmentTime = 0;
1635
+ function getState() {
1636
+ return {
1637
+ thresholds: {
1638
+ groupMaxZoom: baseThresholds.groupMaxZoom + adjustment,
1639
+ subGroupMaxZoom: baseThresholds.subGroupMaxZoom + adjustment
1640
+ },
1641
+ averageFps,
1642
+ adjustment,
1643
+ isAdjusted: adjustment > 0
1644
+ };
1645
+ }
1646
+ return {
1647
+ update(currentFps) {
1648
+ const now = performance.now();
1649
+ averageFps = smoothingFactor * currentFps + (1 - smoothingFactor) * averageFps;
1650
+ if (now - lastAdjustmentTime < adjustmentCooldown) {
1651
+ return getState();
1652
+ }
1653
+ if (averageFps < adjustBelowFps && adjustment < maxAdjustment) {
1654
+ const deficit = adjustBelowFps - averageFps;
1655
+ const newAdjustment = Math.min(
1656
+ maxAdjustment,
1657
+ adjustment + adjustmentStep * Math.ceil(deficit / 10)
1658
+ );
1659
+ if (newAdjustment !== adjustment) {
1660
+ adjustment = newAdjustment;
1661
+ lastAdjustmentTime = now;
1662
+ }
1663
+ } else if (averageFps >= targetFps && adjustment > 0) {
1664
+ const newAdjustment = Math.max(0, adjustment - adjustmentStep);
1665
+ if (newAdjustment !== adjustment) {
1666
+ adjustment = newAdjustment;
1667
+ lastAdjustmentTime = now;
1668
+ }
1669
+ }
1670
+ return getState();
1671
+ },
1672
+ reset() {
1673
+ averageFps = targetFps;
1674
+ adjustment = 0;
1675
+ lastAdjustmentTime = 0;
1676
+ return getState();
1677
+ },
1678
+ getState
1679
+ };
1680
+ }
1681
+ function getSimplificationToleranceForZoom(zoom, baseToleranceAtZoom14 = 2e-5) {
1682
+ const zoomDiff = Math.max(0, 14 - zoom);
1683
+ const multiplier = Math.pow(2, zoomDiff / 2);
1684
+ return baseToleranceAtZoom14 * multiplier;
1685
+ }
1686
+ var DEFAULT_SIMPLIFICATION_THRESHOLDS = [
1687
+ { maxZoom: 14, tolerance: 2e-5 },
1688
+ // Light: ~2m
1689
+ { maxZoom: 13, tolerance: 5e-5 },
1690
+ // Medium-light: ~5m
1691
+ { maxZoom: 12, tolerance: 1e-4 },
1692
+ // Medium: ~11m
1693
+ { maxZoom: 11, tolerance: 2e-4 },
1694
+ // Medium-heavy: ~22m
1695
+ { maxZoom: 10, tolerance: 5e-4 }
1696
+ // Heavy: ~55m
1697
+ ];
1698
+ function buildSpatialIndex(geojson, options = {}) {
1699
+ const { targetCells = 100, minCellSize = 1e-3 } = options;
1700
+ const bounds = calculateBounds(geojson);
1701
+ if (!bounds) {
1702
+ return {
1703
+ grid: /* @__PURE__ */ new Map(),
1704
+ cols: 0,
1705
+ rows: 0,
1706
+ bounds: [
1707
+ [0, 0],
1708
+ [0, 0]
1709
+ ],
1710
+ cellWidth: 0,
1711
+ cellHeight: 0,
1712
+ featureCount: 0
1713
+ };
1714
+ }
1715
+ const [[minLng, minLat], [maxLng, maxLat]] = bounds;
1716
+ const width = maxLng - minLng;
1717
+ const height = maxLat - minLat;
1718
+ const aspectRatio = width / height;
1719
+ let cols = Math.ceil(Math.sqrt(targetCells * aspectRatio));
1720
+ let rows = Math.ceil(targetCells / cols);
1721
+ const cellWidth = Math.max(width / cols, minCellSize);
1722
+ const cellHeight = Math.max(height / rows, minCellSize);
1723
+ cols = Math.ceil(width / cellWidth);
1724
+ rows = Math.ceil(height / cellHeight);
1725
+ const grid = /* @__PURE__ */ new Map();
1726
+ for (const feature of geojson.features) {
1727
+ const featureBounds = getFeatureBounds(feature);
1728
+ if (!featureBounds) continue;
1729
+ const [[fMinLng, fMinLat], [fMaxLng, fMaxLat]] = featureBounds;
1730
+ const minCol = Math.max(0, Math.floor((fMinLng - minLng) / cellWidth));
1731
+ const maxCol = Math.min(cols - 1, Math.floor((fMaxLng - minLng) / cellWidth));
1732
+ const minRow = Math.max(0, Math.floor((fMinLat - minLat) / cellHeight));
1733
+ const maxRow = Math.min(rows - 1, Math.floor((fMaxLat - minLat) / cellHeight));
1734
+ for (let col = minCol; col <= maxCol; col++) {
1735
+ for (let row = minRow; row <= maxRow; row++) {
1736
+ const key = `${col},${row}`;
1737
+ if (!grid.has(key)) {
1738
+ grid.set(key, { features: [] });
1739
+ }
1740
+ grid.get(key).features.push(feature);
1741
+ }
1742
+ }
1743
+ }
1744
+ return {
1745
+ grid,
1746
+ cols,
1747
+ rows,
1748
+ bounds,
1749
+ cellWidth,
1750
+ cellHeight,
1751
+ featureCount: geojson.features.length
1752
+ };
1753
+ }
1754
+ function getFeatureBounds(feature) {
1755
+ const geometry = feature.geometry;
1756
+ if (!geometry) return null;
1757
+ let minLng = Infinity;
1758
+ let minLat = Infinity;
1759
+ let maxLng = -Infinity;
1760
+ let maxLat = -Infinity;
1761
+ function processCoord(coord) {
1762
+ minLng = Math.min(minLng, coord[0]);
1763
+ minLat = Math.min(minLat, coord[1]);
1764
+ maxLng = Math.max(maxLng, coord[0]);
1765
+ maxLat = Math.max(maxLat, coord[1]);
1766
+ }
1767
+ function processRing(ring) {
1768
+ ring.forEach(processCoord);
1769
+ }
1770
+ switch (geometry.type) {
1771
+ case "Point":
1772
+ processCoord(geometry.coordinates);
1773
+ break;
1774
+ case "MultiPoint":
1775
+ case "LineString":
1776
+ geometry.coordinates.forEach(processCoord);
1777
+ break;
1778
+ case "MultiLineString":
1779
+ case "Polygon":
1780
+ geometry.coordinates.forEach(processRing);
1781
+ break;
1782
+ case "MultiPolygon":
1783
+ geometry.coordinates.forEach(
1784
+ (polygon) => polygon.forEach(processRing)
1785
+ );
1786
+ break;
1787
+ }
1788
+ if (minLng === Infinity) return null;
1789
+ return [
1790
+ [minLng, minLat],
1791
+ [maxLng, maxLat]
1792
+ ];
1793
+ }
1794
+ function queryByBounds(index, queryBounds, options = {}) {
1795
+ const { buffer = 0.01, bufferFraction } = options;
1796
+ if (index.featureCount === 0) {
1797
+ return { type: "FeatureCollection", features: [] };
1798
+ }
1799
+ let [[minLng, minLat], [maxLng, maxLat]] = normalizeBounds(queryBounds);
1800
+ const viewWidth = maxLng - minLng;
1801
+ const viewHeight = maxLat - minLat;
1802
+ const actualBuffer = bufferFraction ? Math.max(viewWidth, viewHeight) * bufferFraction : buffer;
1803
+ minLng -= actualBuffer;
1804
+ minLat -= actualBuffer;
1805
+ maxLng += actualBuffer;
1806
+ maxLat += actualBuffer;
1807
+ const [[idxMinLng, idxMinLat]] = index.bounds;
1808
+ const minCol = Math.max(0, Math.floor((minLng - idxMinLng) / index.cellWidth));
1809
+ const maxCol = Math.min(index.cols - 1, Math.floor((maxLng - idxMinLng) / index.cellWidth));
1810
+ const minRow = Math.max(0, Math.floor((minLat - idxMinLat) / index.cellHeight));
1811
+ const maxRow = Math.min(index.rows - 1, Math.floor((maxLat - idxMinLat) / index.cellHeight));
1812
+ const seen = /* @__PURE__ */ new Set();
1813
+ const features = [];
1814
+ for (let col = minCol; col <= maxCol; col++) {
1815
+ for (let row = minRow; row <= maxRow; row++) {
1816
+ const cell = index.grid.get(`${col},${row}`);
1817
+ if (cell) {
1818
+ for (const feature of cell.features) {
1819
+ if (!seen.has(feature)) {
1820
+ const featureBounds = getFeatureBounds(feature);
1821
+ if (featureBounds && boundsIntersect(featureBounds, [
1822
+ [minLng, minLat],
1823
+ [maxLng, maxLat]
1824
+ ])) {
1825
+ seen.add(feature);
1826
+ features.push(feature);
1827
+ }
1828
+ }
1829
+ }
1830
+ }
1831
+ }
1832
+ }
1833
+ return { type: "FeatureCollection", features };
1834
+ }
1835
+ function boundsIntersect(a, b) {
1836
+ return !(a[1][0] < b[0][0] || // a is left of b
1837
+ a[0][0] > b[1][0] || // a is right of b
1838
+ a[1][1] < b[0][1] || // a is below b
1839
+ a[0][1] > b[1][1]);
1840
+ }
1841
+ function normalizeBounds(bounds) {
1842
+ if (Array.isArray(bounds) && Array.isArray(bounds[0])) {
1843
+ return bounds;
1844
+ }
1845
+ const mapBounds = bounds;
1846
+ return [mapBounds.southwest, mapBounds.northeast];
1847
+ }
1848
+ function queryByBoundsWithStats(index, queryBounds, options = {}) {
1849
+ const { buffer = 0.01, bufferFraction } = options;
1850
+ if (index.featureCount === 0) {
1851
+ return {
1852
+ data: { type: "FeatureCollection", features: [] },
1853
+ stats: {
1854
+ totalFeatures: 0,
1855
+ visibleFeatures: 0,
1856
+ culledPercent: 0,
1857
+ cellsChecked: 0,
1858
+ totalCells: 0
1859
+ }
1860
+ };
1861
+ }
1862
+ let [[minLng, minLat], [maxLng, maxLat]] = normalizeBounds(queryBounds);
1863
+ const viewWidth = maxLng - minLng;
1864
+ const viewHeight = maxLat - minLat;
1865
+ const actualBuffer = bufferFraction ? Math.max(viewWidth, viewHeight) * bufferFraction : buffer;
1866
+ minLng -= actualBuffer;
1867
+ minLat -= actualBuffer;
1868
+ maxLng += actualBuffer;
1869
+ maxLat += actualBuffer;
1870
+ const [[idxMinLng, idxMinLat]] = index.bounds;
1871
+ const minCol = Math.max(0, Math.floor((minLng - idxMinLng) / index.cellWidth));
1872
+ const maxCol = Math.min(index.cols - 1, Math.floor((maxLng - idxMinLng) / index.cellWidth));
1873
+ const minRow = Math.max(0, Math.floor((minLat - idxMinLat) / index.cellHeight));
1874
+ const maxRow = Math.min(index.rows - 1, Math.floor((maxLat - idxMinLat) / index.cellHeight));
1875
+ const seen = /* @__PURE__ */ new Set();
1876
+ const features = [];
1877
+ let cellsChecked = 0;
1878
+ for (let col = minCol; col <= maxCol; col++) {
1879
+ for (let row = minRow; row <= maxRow; row++) {
1880
+ cellsChecked++;
1881
+ const cell = index.grid.get(`${col},${row}`);
1882
+ if (cell) {
1883
+ for (const feature of cell.features) {
1884
+ if (!seen.has(feature)) {
1885
+ const featureBounds = getFeatureBounds(feature);
1886
+ if (featureBounds && boundsIntersect(featureBounds, [
1887
+ [minLng, minLat],
1888
+ [maxLng, maxLat]
1889
+ ])) {
1890
+ seen.add(feature);
1891
+ features.push(feature);
1892
+ }
1893
+ }
1894
+ }
1895
+ }
1896
+ }
1897
+ }
1898
+ const visibleFeatures = features.length;
1899
+ const culledPercent = index.featureCount > 0 ? (index.featureCount - visibleFeatures) / index.featureCount * 100 : 0;
1900
+ return {
1901
+ data: { type: "FeatureCollection", features },
1902
+ stats: {
1903
+ totalFeatures: index.featureCount,
1904
+ visibleFeatures,
1905
+ culledPercent,
1906
+ cellsChecked,
1907
+ totalCells: index.cols * index.rows
1908
+ }
1909
+ };
1910
+ }
1911
+ function createViewportQuery(index, options) {
1912
+ const { debounceMs = 50, bufferFraction = 0.2, onUpdate } = options;
1913
+ let timeoutId = null;
1914
+ let lastBounds = null;
1915
+ return (bounds) => {
1916
+ lastBounds = bounds;
1917
+ if (timeoutId) {
1918
+ clearTimeout(timeoutId);
1919
+ }
1920
+ timeoutId = setTimeout(() => {
1921
+ if (lastBounds) {
1922
+ const { data, stats } = queryByBoundsWithStats(index, lastBounds, {
1923
+ bufferFraction
1924
+ });
1925
+ onUpdate(data, stats);
1926
+ }
1927
+ timeoutId = null;
1928
+ }, debounceMs);
1929
+ };
1930
+ }
1931
+ function createViewportManager(index, options = {}) {
1932
+ const { bufferFraction = 0.25, minMovement = 0.1 } = options;
1933
+ let lastBounds = null;
1934
+ let lastData = null;
1935
+ let lastStats = null;
1936
+ function shouldUpdate(newBounds) {
1937
+ if (!lastBounds) return true;
1938
+ const lastWidth = lastBounds[1][0] - lastBounds[0][0];
1939
+ const lastHeight = lastBounds[1][1] - lastBounds[0][1];
1940
+ const movementLng = Math.abs(
1941
+ (newBounds[0][0] + newBounds[1][0]) / 2 - (lastBounds[0][0] + lastBounds[1][0]) / 2
1942
+ );
1943
+ const movementLat = Math.abs(
1944
+ (newBounds[0][1] + newBounds[1][1]) / 2 - (lastBounds[0][1] + lastBounds[1][1]) / 2
1945
+ );
1946
+ const movement = Math.max(movementLng / lastWidth, movementLat / lastHeight);
1947
+ const newWidth = newBounds[1][0] - newBounds[0][0];
1948
+ const zoomChange = Math.abs(newWidth / lastWidth - 1);
1949
+ return movement > minMovement || zoomChange > 0.2;
1950
+ }
1951
+ return {
1952
+ update(bounds) {
1953
+ const normalizedBounds = normalizeBounds(bounds);
1954
+ if (lastData && !shouldUpdate(normalizedBounds)) {
1955
+ return {
1956
+ data: lastData,
1957
+ stats: lastStats,
1958
+ updated: false
1959
+ };
1960
+ }
1961
+ const { data, stats } = queryByBoundsWithStats(index, normalizedBounds, {
1962
+ bufferFraction
1963
+ });
1964
+ lastBounds = normalizedBounds;
1965
+ lastData = data;
1966
+ lastStats = stats;
1967
+ return {
1968
+ data,
1969
+ stats,
1970
+ updated: true
1971
+ };
1972
+ },
1973
+ reset() {
1974
+ lastBounds = null;
1975
+ lastData = null;
1976
+ lastStats = null;
1977
+ },
1978
+ getStats() {
1979
+ return lastStats;
1980
+ }
1981
+ };
1982
+ }
1983
+ var requestIdleCallbackPolyfill = typeof requestIdleCallback !== "undefined" ? requestIdleCallback : (cb, options) => {
1984
+ const start = Date.now();
1985
+ return setTimeout(() => {
1986
+ cb({
1987
+ didTimeout: true,
1988
+ timeRemaining: () => Math.max(0, 50 - (Date.now() - start))
1989
+ });
1990
+ }, options?.timeout ?? 1);
1991
+ };
1992
+ var cancelIdleCallbackPolyfill = typeof cancelIdleCallback !== "undefined" ? cancelIdleCallback : (id) => clearTimeout(id);
1993
+ function createIdleViewportManager(index, options = {}) {
1994
+ const {
1995
+ bufferFraction = 0.25,
1996
+ minMovement = 0.1,
1997
+ maxUpdatesPerSecond = 12,
1998
+ idleDelay = 100,
1999
+ predictivePan = true,
2000
+ predictiveMultiplier = 2,
2001
+ velocitySamples = 5,
2002
+ maxPanDistance = 0.5
2003
+ } = options;
2004
+ const minUpdateInterval = 1e3 / maxUpdatesPerSecond;
2005
+ let lastBounds = null;
2006
+ let lastDataFetchBounds = null;
2007
+ let lastData = null;
2008
+ let lastStats = null;
2009
+ let pendingIdleId = null;
2010
+ let pendingBounds = null;
2011
+ let lastUpdateTime = 0;
2012
+ let viewportSamples = [];
2013
+ let currentVelocity = { lngPerSec: 0, latPerSec: 0, magnitude: 0 };
2014
+ let dataReadyCallback = null;
2015
+ const isRTree = "tree" in index;
2016
+ function getCumulativeDistance(newBounds) {
2017
+ if (!lastDataFetchBounds) return Infinity;
2018
+ const viewWidth = newBounds[1][0] - newBounds[0][0];
2019
+ const viewHeight = newBounds[1][1] - newBounds[0][1];
2020
+ const fetchCenterLng = (lastDataFetchBounds[0][0] + lastDataFetchBounds[1][0]) / 2;
2021
+ const fetchCenterLat = (lastDataFetchBounds[0][1] + lastDataFetchBounds[1][1]) / 2;
2022
+ const newCenterLng = (newBounds[0][0] + newBounds[1][0]) / 2;
2023
+ const newCenterLat = (newBounds[0][1] + newBounds[1][1]) / 2;
2024
+ const distLng = Math.abs(newCenterLng - fetchCenterLng) / viewWidth;
2025
+ const distLat = Math.abs(newCenterLat - fetchCenterLat) / viewHeight;
2026
+ return Math.max(distLng, distLat);
2027
+ }
2028
+ function shouldUpdate(newBounds) {
2029
+ if (!lastBounds) return true;
2030
+ const lastWidth = lastBounds[1][0] - lastBounds[0][0];
2031
+ const lastHeight = lastBounds[1][1] - lastBounds[0][1];
2032
+ const movementLng = Math.abs(
2033
+ (newBounds[0][0] + newBounds[1][0]) / 2 - (lastBounds[0][0] + lastBounds[1][0]) / 2
2034
+ );
2035
+ const movementLat = Math.abs(
2036
+ (newBounds[0][1] + newBounds[1][1]) / 2 - (lastBounds[0][1] + lastBounds[1][1]) / 2
2037
+ );
2038
+ const movement = Math.max(movementLng / lastWidth, movementLat / lastHeight);
2039
+ const newWidth = newBounds[1][0] - newBounds[0][0];
2040
+ const zoomChange = Math.abs(newWidth / lastWidth - 1);
2041
+ const cumulativeDistance = getCumulativeDistance(newBounds);
2042
+ return movement > minMovement || zoomChange > 0.2 || cumulativeDistance > maxPanDistance;
2043
+ }
2044
+ function trackVelocity(normalizedBounds) {
2045
+ const now = performance.now();
2046
+ const center = [
2047
+ (normalizedBounds[0][0] + normalizedBounds[1][0]) / 2,
2048
+ (normalizedBounds[0][1] + normalizedBounds[1][1]) / 2
2049
+ ];
2050
+ viewportSamples.push({ center, timestamp: now });
2051
+ while (viewportSamples.length > velocitySamples) {
2052
+ viewportSamples.shift();
2053
+ }
2054
+ currentVelocity = calculatePanVelocityInternal(viewportSamples);
2055
+ }
2056
+ function executeQuery(normalizedBounds) {
2057
+ const viewWidth = normalizedBounds[1][0] - normalizedBounds[0][0];
2058
+ const viewHeight = normalizedBounds[1][1] - normalizedBounds[0][1];
2059
+ const baseBuffer = Math.max(viewWidth, viewHeight) * bufferFraction;
2060
+ let queryBounds = normalizedBounds;
2061
+ if (predictivePan && currentVelocity.magnitude > 1e-5) {
2062
+ queryBounds = applyPredictiveBufferInternal(
2063
+ normalizedBounds,
2064
+ currentVelocity,
2065
+ baseBuffer,
2066
+ predictiveMultiplier
2067
+ );
2068
+ } else {
2069
+ queryBounds = [
2070
+ [normalizedBounds[0][0] - baseBuffer, normalizedBounds[0][1] - baseBuffer],
2071
+ [normalizedBounds[1][0] + baseBuffer, normalizedBounds[1][1] + baseBuffer]
2072
+ ];
2073
+ }
2074
+ let data;
2075
+ let stats;
2076
+ if (isRTree) {
2077
+ const rtreeIndex = index;
2078
+ const result = queryRTreeByBoundsWithStats(rtreeIndex, queryBounds, {
2079
+ buffer: 0
2080
+ // Buffer already applied
2081
+ });
2082
+ data = result.data;
2083
+ stats = {
2084
+ totalFeatures: result.stats.totalFeatures,
2085
+ visibleFeatures: result.stats.visibleFeatures,
2086
+ culledPercent: result.stats.culledPercent,
2087
+ cellsChecked: 0,
2088
+ totalCells: 0
2089
+ };
2090
+ } else {
2091
+ const gridIndex = index;
2092
+ const result = queryByBoundsWithStats(gridIndex, queryBounds, {
2093
+ buffer: 0
2094
+ // Buffer already applied
2095
+ });
2096
+ data = result.data;
2097
+ stats = result.stats;
2098
+ }
2099
+ lastBounds = normalizedBounds;
2100
+ lastDataFetchBounds = normalizedBounds;
2101
+ lastData = data;
2102
+ lastStats = stats;
2103
+ lastUpdateTime = performance.now();
2104
+ return {
2105
+ data,
2106
+ stats,
2107
+ updated: true,
2108
+ velocity: currentVelocity
2109
+ };
2110
+ }
2111
+ function cancelPending() {
2112
+ if (pendingIdleId !== null) {
2113
+ cancelIdleCallbackPolyfill(pendingIdleId);
2114
+ pendingIdleId = null;
2115
+ }
2116
+ pendingBounds = null;
2117
+ }
2118
+ return {
2119
+ queueUpdate(bounds, trackOnly = false) {
2120
+ const normalizedBounds = normalizeBoundsInternal(bounds);
2121
+ trackVelocity(normalizedBounds);
2122
+ const cumulativeDistance = getCumulativeDistance(normalizedBounds);
2123
+ const mustUpdate = cumulativeDistance > maxPanDistance;
2124
+ if (trackOnly) {
2125
+ if (mustUpdate) {
2126
+ const result = executeQuery(normalizedBounds);
2127
+ result.chunkLoadTriggered = true;
2128
+ if (dataReadyCallback) {
2129
+ dataReadyCallback(result);
2130
+ }
2131
+ }
2132
+ return;
2133
+ }
2134
+ if (lastData && !shouldUpdate(normalizedBounds) && !mustUpdate) {
2135
+ return;
2136
+ }
2137
+ const now = performance.now();
2138
+ if (!mustUpdate && now - lastUpdateTime < minUpdateInterval) {
2139
+ pendingBounds = normalizedBounds;
2140
+ if (pendingIdleId === null) {
2141
+ pendingIdleId = requestIdleCallbackPolyfill(
2142
+ () => {
2143
+ pendingIdleId = null;
2144
+ if (pendingBounds) {
2145
+ const result = executeQuery(pendingBounds);
2146
+ pendingBounds = null;
2147
+ if (dataReadyCallback) {
2148
+ dataReadyCallback(result);
2149
+ }
2150
+ }
2151
+ },
2152
+ { timeout: idleDelay }
2153
+ );
2154
+ }
2155
+ return;
2156
+ }
2157
+ cancelPending();
2158
+ if (mustUpdate) {
2159
+ const result = executeQuery(normalizedBounds);
2160
+ result.chunkLoadTriggered = true;
2161
+ if (dataReadyCallback) {
2162
+ dataReadyCallback(result);
2163
+ }
2164
+ return;
2165
+ }
2166
+ pendingBounds = normalizedBounds;
2167
+ pendingIdleId = requestIdleCallbackPolyfill(
2168
+ () => {
2169
+ pendingIdleId = null;
2170
+ if (pendingBounds) {
2171
+ const result = executeQuery(pendingBounds);
2172
+ pendingBounds = null;
2173
+ if (dataReadyCallback) {
2174
+ dataReadyCallback(result);
2175
+ }
2176
+ }
2177
+ },
2178
+ { timeout: idleDelay }
2179
+ );
2180
+ },
2181
+ forceUpdate(bounds) {
2182
+ const normalizedBounds = normalizeBoundsInternal(bounds);
2183
+ cancelPending();
2184
+ trackVelocity(normalizedBounds);
2185
+ if (lastData && !shouldUpdate(normalizedBounds)) {
2186
+ return {
2187
+ data: lastData,
2188
+ stats: lastStats,
2189
+ updated: false,
2190
+ velocity: currentVelocity
2191
+ };
2192
+ }
2193
+ return executeQuery(normalizedBounds);
2194
+ },
2195
+ onDataReady(callback) {
2196
+ dataReadyCallback = callback;
2197
+ },
2198
+ reset() {
2199
+ cancelPending();
2200
+ lastBounds = null;
2201
+ lastDataFetchBounds = null;
2202
+ lastData = null;
2203
+ lastStats = null;
2204
+ lastUpdateTime = 0;
2205
+ viewportSamples = [];
2206
+ currentVelocity = { lngPerSec: 0, latPerSec: 0, magnitude: 0 };
2207
+ },
2208
+ getStats() {
2209
+ return lastStats;
2210
+ },
2211
+ getVelocity() {
2212
+ return currentVelocity;
2213
+ },
2214
+ getCumulativeDistance(bounds) {
2215
+ return getCumulativeDistance(normalizeBoundsInternal(bounds));
2216
+ }
2217
+ };
2218
+ }
2219
+ function calculatePanVelocityInternal(samples) {
2220
+ if (samples.length < 2) {
2221
+ return { lngPerSec: 0, latPerSec: 0, magnitude: 0 };
2222
+ }
2223
+ let totalLngDelta = 0;
2224
+ let totalLatDelta = 0;
2225
+ let totalTime = 0;
2226
+ let weight = 1;
2227
+ for (let i = samples.length - 1; i > 0; i--) {
2228
+ const current = samples[i];
2229
+ const previous = samples[i - 1];
2230
+ const dt = (current.timestamp - previous.timestamp) / 1e3;
2231
+ if (dt > 0 && dt < 1) {
2232
+ totalLngDelta += (current.center[0] - previous.center[0]) * weight;
2233
+ totalLatDelta += (current.center[1] - previous.center[1]) * weight;
2234
+ totalTime += dt * weight;
2235
+ }
2236
+ weight *= 0.7;
2237
+ }
2238
+ if (totalTime === 0) {
2239
+ return { lngPerSec: 0, latPerSec: 0, magnitude: 0 };
2240
+ }
2241
+ const lngPerSec = totalLngDelta / totalTime;
2242
+ const latPerSec = totalLatDelta / totalTime;
2243
+ const magnitude = Math.sqrt(lngPerSec * lngPerSec + latPerSec * latPerSec);
2244
+ return { lngPerSec, latPerSec, magnitude };
2245
+ }
2246
+ function applyPredictiveBufferInternal(bounds, velocity, baseBuffer, multiplier) {
2247
+ const [[minLng, minLat], [maxLng, maxLat]] = bounds;
2248
+ let bufferMinLng = baseBuffer;
2249
+ let bufferMaxLng = baseBuffer;
2250
+ let bufferMinLat = baseBuffer;
2251
+ let bufferMaxLat = baseBuffer;
2252
+ if (velocity.magnitude > 1e-5) {
2253
+ const extraBuffer = baseBuffer * (multiplier - 1);
2254
+ if (velocity.lngPerSec > 0) {
2255
+ bufferMaxLng += extraBuffer * Math.min(1, velocity.lngPerSec / velocity.magnitude);
2256
+ } else if (velocity.lngPerSec < 0) {
2257
+ bufferMinLng += extraBuffer * Math.min(1, -velocity.lngPerSec / velocity.magnitude);
2258
+ }
2259
+ if (velocity.latPerSec > 0) {
2260
+ bufferMaxLat += extraBuffer * Math.min(1, velocity.latPerSec / velocity.magnitude);
2261
+ } else if (velocity.latPerSec < 0) {
2262
+ bufferMinLat += extraBuffer * Math.min(1, -velocity.latPerSec / velocity.magnitude);
2263
+ }
2264
+ }
2265
+ return [
2266
+ [minLng - bufferMinLng, minLat - bufferMinLat],
2267
+ [maxLng + bufferMaxLng, maxLat + bufferMaxLat]
2268
+ ];
2269
+ }
2270
+ function calculatePanVelocity(samples) {
2271
+ if (samples.length < 2) {
2272
+ return { lngPerSec: 0, latPerSec: 0, magnitude: 0 };
2273
+ }
2274
+ let totalLngDelta = 0;
2275
+ let totalLatDelta = 0;
2276
+ let totalTime = 0;
2277
+ let weight = 1;
2278
+ for (let i = samples.length - 1; i > 0; i--) {
2279
+ const current = samples[i];
2280
+ const previous = samples[i - 1];
2281
+ const dt = (current.timestamp - previous.timestamp) / 1e3;
2282
+ if (dt > 0 && dt < 1) {
2283
+ totalLngDelta += (current.center[0] - previous.center[0]) * weight;
2284
+ totalLatDelta += (current.center[1] - previous.center[1]) * weight;
2285
+ totalTime += dt * weight;
2286
+ }
2287
+ weight *= 0.7;
2288
+ }
2289
+ if (totalTime === 0) {
2290
+ return { lngPerSec: 0, latPerSec: 0, magnitude: 0 };
2291
+ }
2292
+ const lngPerSec = totalLngDelta / totalTime;
2293
+ const latPerSec = totalLatDelta / totalTime;
2294
+ const magnitude = Math.sqrt(lngPerSec * lngPerSec + latPerSec * latPerSec);
2295
+ return { lngPerSec, latPerSec, magnitude };
2296
+ }
2297
+ function applyPredictiveBuffer(bounds, velocity, baseBuffer, multiplier) {
2298
+ const [[minLng, minLat], [maxLng, maxLat]] = bounds;
2299
+ let bufferMinLng = baseBuffer;
2300
+ let bufferMaxLng = baseBuffer;
2301
+ let bufferMinLat = baseBuffer;
2302
+ let bufferMaxLat = baseBuffer;
2303
+ if (velocity.magnitude > 1e-5) {
2304
+ const extraBuffer = baseBuffer * (multiplier - 1);
2305
+ if (velocity.lngPerSec > 0) {
2306
+ bufferMaxLng += extraBuffer * Math.min(1, velocity.lngPerSec / velocity.magnitude);
2307
+ } else if (velocity.lngPerSec < 0) {
2308
+ bufferMinLng += extraBuffer * Math.min(1, -velocity.lngPerSec / velocity.magnitude);
2309
+ }
2310
+ if (velocity.latPerSec > 0) {
2311
+ bufferMaxLat += extraBuffer * Math.min(1, velocity.latPerSec / velocity.magnitude);
2312
+ } else if (velocity.latPerSec < 0) {
2313
+ bufferMinLat += extraBuffer * Math.min(1, -velocity.latPerSec / velocity.magnitude);
2314
+ }
2315
+ }
2316
+ return [
2317
+ [minLng - bufferMinLng, minLat - bufferMinLat],
2318
+ [maxLng + bufferMaxLng, maxLat + bufferMaxLat]
2319
+ ];
2320
+ }
2321
+ function createPredictiveViewportManager(index, options = {}) {
2322
+ const {
2323
+ bufferFraction = 0.25,
2324
+ minMovement = 0.1,
2325
+ predictiveMultiplier = 2,
2326
+ velocitySamples = 5
2327
+ } = options;
2328
+ let lastBounds = null;
2329
+ let lastData = null;
2330
+ let lastStats = null;
2331
+ let viewportSamples = [];
2332
+ let currentVelocity = { lngPerSec: 0, latPerSec: 0, magnitude: 0 };
2333
+ const isRTree = "tree" in index;
2334
+ function shouldUpdate(newBounds) {
2335
+ if (!lastBounds) return true;
2336
+ const lastWidth = lastBounds[1][0] - lastBounds[0][0];
2337
+ const lastHeight = lastBounds[1][1] - lastBounds[0][1];
2338
+ const movementLng = Math.abs(
2339
+ (newBounds[0][0] + newBounds[1][0]) / 2 - (lastBounds[0][0] + lastBounds[1][0]) / 2
2340
+ );
2341
+ const movementLat = Math.abs(
2342
+ (newBounds[0][1] + newBounds[1][1]) / 2 - (lastBounds[0][1] + lastBounds[1][1]) / 2
2343
+ );
2344
+ const movement = Math.max(movementLng / lastWidth, movementLat / lastHeight);
2345
+ const newWidth = newBounds[1][0] - newBounds[0][0];
2346
+ const zoomChange = Math.abs(newWidth / lastWidth - 1);
2347
+ return movement > minMovement || zoomChange > 0.2;
2348
+ }
2349
+ return {
2350
+ update(bounds) {
2351
+ const normalizedBounds = normalizeBounds(bounds);
2352
+ const now = performance.now();
2353
+ const center = [
2354
+ (normalizedBounds[0][0] + normalizedBounds[1][0]) / 2,
2355
+ (normalizedBounds[0][1] + normalizedBounds[1][1]) / 2
2356
+ ];
2357
+ viewportSamples.push({ center, timestamp: now });
2358
+ while (viewportSamples.length > velocitySamples) {
2359
+ viewportSamples.shift();
2360
+ }
2361
+ currentVelocity = calculatePanVelocity(viewportSamples);
2362
+ if (lastData && !shouldUpdate(normalizedBounds)) {
2363
+ return {
2364
+ data: lastData,
2365
+ stats: lastStats,
2366
+ updated: false,
2367
+ velocity: currentVelocity
2368
+ };
2369
+ }
2370
+ const viewWidth = normalizedBounds[1][0] - normalizedBounds[0][0];
2371
+ const viewHeight = normalizedBounds[1][1] - normalizedBounds[0][1];
2372
+ const baseBuffer = Math.max(viewWidth, viewHeight) * bufferFraction;
2373
+ const predictiveBounds = applyPredictiveBuffer(
2374
+ normalizedBounds,
2375
+ currentVelocity,
2376
+ baseBuffer,
2377
+ predictiveMultiplier
2378
+ );
2379
+ let data;
2380
+ let stats;
2381
+ if (isRTree) {
2382
+ const rtreeIndex = index;
2383
+ const result = queryRTreeByBoundsWithStats(rtreeIndex, predictiveBounds, {
2384
+ buffer: 0
2385
+ // Buffer already applied
2386
+ });
2387
+ data = result.data;
2388
+ stats = {
2389
+ totalFeatures: result.stats.totalFeatures,
2390
+ visibleFeatures: result.stats.visibleFeatures,
2391
+ culledPercent: result.stats.culledPercent,
2392
+ cellsChecked: 0,
2393
+ totalCells: 0
2394
+ };
2395
+ } else {
2396
+ const gridIndex = index;
2397
+ const result = queryByBoundsWithStats(gridIndex, predictiveBounds, {
2398
+ buffer: 0
2399
+ // Buffer already applied
2400
+ });
2401
+ data = result.data;
2402
+ stats = result.stats;
2403
+ }
2404
+ lastBounds = normalizedBounds;
2405
+ lastData = data;
2406
+ lastStats = stats;
2407
+ return {
2408
+ data,
2409
+ stats,
2410
+ updated: true,
2411
+ velocity: currentVelocity
2412
+ };
2413
+ },
2414
+ reset() {
2415
+ lastBounds = null;
2416
+ lastData = null;
2417
+ lastStats = null;
2418
+ viewportSamples = [];
2419
+ currentVelocity = { lngPerSec: 0, latPerSec: 0, magnitude: 0 };
2420
+ },
2421
+ getStats() {
2422
+ return lastStats;
2423
+ },
2424
+ getVelocity() {
2425
+ return currentVelocity;
2426
+ }
2427
+ };
2428
+ }
2429
+ function buildRTreeIndex(geojson, options = {}) {
2430
+ const { maxEntries = 9 } = options;
2431
+ const tree = new RBush(maxEntries);
2432
+ const items = [];
2433
+ let minLngAll = Infinity;
2434
+ let minLatAll = Infinity;
2435
+ let maxLngAll = -Infinity;
2436
+ let maxLatAll = -Infinity;
2437
+ for (const feature of geojson.features) {
2438
+ const featureBounds = getFeatureBoundsInternal(feature);
2439
+ if (!featureBounds) continue;
2440
+ const [[minLng, minLat], [maxLng, maxLat]] = featureBounds;
2441
+ items.push({
2442
+ minX: minLng,
2443
+ minY: minLat,
2444
+ maxX: maxLng,
2445
+ maxY: maxLat,
2446
+ feature
2447
+ });
2448
+ minLngAll = Math.min(minLngAll, minLng);
2449
+ minLatAll = Math.min(minLatAll, minLat);
2450
+ maxLngAll = Math.max(maxLngAll, maxLng);
2451
+ maxLatAll = Math.max(maxLatAll, maxLat);
2452
+ }
2453
+ tree.load(items);
2454
+ const bounds = minLngAll === Infinity ? [
2455
+ [0, 0],
2456
+ [0, 0]
2457
+ ] : [
2458
+ [minLngAll, minLatAll],
2459
+ [maxLngAll, maxLatAll]
2460
+ ];
2461
+ return {
2462
+ tree,
2463
+ bounds,
2464
+ featureCount: items.length
2465
+ };
2466
+ }
2467
+ function getFeatureBoundsInternal(feature) {
2468
+ const geometry = feature.geometry;
2469
+ if (!geometry) return null;
2470
+ let minLng = Infinity;
2471
+ let minLat = Infinity;
2472
+ let maxLng = -Infinity;
2473
+ let maxLat = -Infinity;
2474
+ function processCoord(coord) {
2475
+ minLng = Math.min(minLng, coord[0]);
2476
+ minLat = Math.min(minLat, coord[1]);
2477
+ maxLng = Math.max(maxLng, coord[0]);
2478
+ maxLat = Math.max(maxLat, coord[1]);
2479
+ }
2480
+ function processRing(ring) {
2481
+ ring.forEach(processCoord);
2482
+ }
2483
+ switch (geometry.type) {
2484
+ case "Point":
2485
+ processCoord(geometry.coordinates);
2486
+ break;
2487
+ case "MultiPoint":
2488
+ case "LineString":
2489
+ geometry.coordinates.forEach(processCoord);
2490
+ break;
2491
+ case "MultiLineString":
2492
+ case "Polygon":
2493
+ geometry.coordinates.forEach(processRing);
2494
+ break;
2495
+ case "MultiPolygon":
2496
+ geometry.coordinates.forEach(
2497
+ (polygon) => polygon.forEach(processRing)
2498
+ );
2499
+ break;
2500
+ }
2501
+ if (minLng === Infinity) return null;
2502
+ return [
2503
+ [minLng, minLat],
2504
+ [maxLng, maxLat]
2505
+ ];
2506
+ }
2507
+ function queryRTreeByBounds(index, queryBounds, options = {}) {
2508
+ const { buffer = 0.01, bufferFraction } = options;
2509
+ if (index.featureCount === 0) {
2510
+ return { type: "FeatureCollection", features: [] };
2511
+ }
2512
+ let [[minLng, minLat], [maxLng, maxLat]] = normalizeBoundsInternal(queryBounds);
2513
+ const viewWidth = maxLng - minLng;
2514
+ const viewHeight = maxLat - minLat;
2515
+ const actualBuffer = bufferFraction ? Math.max(viewWidth, viewHeight) * bufferFraction : buffer;
2516
+ minLng -= actualBuffer;
2517
+ minLat -= actualBuffer;
2518
+ maxLng += actualBuffer;
2519
+ maxLat += actualBuffer;
2520
+ const results = index.tree.search({
2521
+ minX: minLng,
2522
+ minY: minLat,
2523
+ maxX: maxLng,
2524
+ maxY: maxLat
2525
+ });
2526
+ return {
2527
+ type: "FeatureCollection",
2528
+ features: results.map((item) => item.feature)
2529
+ };
2530
+ }
2531
+ function queryRTreeByBoundsWithStats(index, queryBounds, options = {}) {
2532
+ const { buffer = 0.01, bufferFraction } = options;
2533
+ if (index.featureCount === 0) {
2534
+ return {
2535
+ data: { type: "FeatureCollection", features: [] },
2536
+ stats: {
2537
+ totalFeatures: 0,
2538
+ visibleFeatures: 0,
2539
+ culledPercent: 0,
2540
+ queryTimeMs: 0
2541
+ }
2542
+ };
2543
+ }
2544
+ const startTime = performance.now();
2545
+ let [[minLng, minLat], [maxLng, maxLat]] = normalizeBoundsInternal(queryBounds);
2546
+ const viewWidth = maxLng - minLng;
2547
+ const viewHeight = maxLat - minLat;
2548
+ const actualBuffer = bufferFraction ? Math.max(viewWidth, viewHeight) * bufferFraction : buffer;
2549
+ minLng -= actualBuffer;
2550
+ minLat -= actualBuffer;
2551
+ maxLng += actualBuffer;
2552
+ maxLat += actualBuffer;
2553
+ const results = index.tree.search({
2554
+ minX: minLng,
2555
+ minY: minLat,
2556
+ maxX: maxLng,
2557
+ maxY: maxLat
2558
+ });
2559
+ const queryTimeMs = performance.now() - startTime;
2560
+ const visibleFeatures = results.length;
2561
+ const culledPercent = index.featureCount > 0 ? (index.featureCount - visibleFeatures) / index.featureCount * 100 : 0;
2562
+ return {
2563
+ data: {
2564
+ type: "FeatureCollection",
2565
+ features: results.map((item) => item.feature)
2566
+ },
2567
+ stats: {
2568
+ totalFeatures: index.featureCount,
2569
+ visibleFeatures,
2570
+ culledPercent,
2571
+ queryTimeMs
2572
+ }
2573
+ };
2574
+ }
2575
+ function normalizeBoundsInternal(bounds) {
2576
+ if (Array.isArray(bounds) && Array.isArray(bounds[0])) {
2577
+ return bounds;
2578
+ }
2579
+ const mapBounds = bounds;
2580
+ return [mapBounds.southwest, mapBounds.northeast];
2581
+ }
2582
+ function createRTreeViewportManager(index, options = {}) {
2583
+ const { bufferFraction = 0.25, minMovement = 0.1 } = options;
2584
+ let lastBounds = null;
2585
+ let lastData = null;
2586
+ let lastStats = null;
2587
+ function shouldUpdate(newBounds) {
2588
+ if (!lastBounds) return true;
2589
+ const lastWidth = lastBounds[1][0] - lastBounds[0][0];
2590
+ const lastHeight = lastBounds[1][1] - lastBounds[0][1];
2591
+ const movementLng = Math.abs(
2592
+ (newBounds[0][0] + newBounds[1][0]) / 2 - (lastBounds[0][0] + lastBounds[1][0]) / 2
2593
+ );
2594
+ const movementLat = Math.abs(
2595
+ (newBounds[0][1] + newBounds[1][1]) / 2 - (lastBounds[0][1] + lastBounds[1][1]) / 2
2596
+ );
2597
+ const movement = Math.max(movementLng / lastWidth, movementLat / lastHeight);
2598
+ const newWidth = newBounds[1][0] - newBounds[0][0];
2599
+ const zoomChange = Math.abs(newWidth / lastWidth - 1);
2600
+ return movement > minMovement || zoomChange > 0.2;
2601
+ }
2602
+ return {
2603
+ update(bounds) {
2604
+ const normalizedBounds = normalizeBoundsInternal(bounds);
2605
+ if (lastData && !shouldUpdate(normalizedBounds)) {
2606
+ return {
2607
+ data: lastData,
2608
+ stats: lastStats,
2609
+ updated: false,
2610
+ queryTimeMs: lastStats?.queryTimeMs
2611
+ };
2612
+ }
2613
+ const { data, stats } = queryRTreeByBoundsWithStats(index, normalizedBounds, {
2614
+ bufferFraction
2615
+ });
2616
+ lastBounds = normalizedBounds;
2617
+ lastData = data;
2618
+ lastStats = {
2619
+ totalFeatures: stats.totalFeatures,
2620
+ visibleFeatures: stats.visibleFeatures,
2621
+ culledPercent: stats.culledPercent,
2622
+ cellsChecked: 0,
2623
+ // R-tree doesn't use cells
2624
+ totalCells: 0,
2625
+ queryTimeMs: stats.queryTimeMs
2626
+ };
2627
+ return {
2628
+ data,
2629
+ stats: lastStats,
2630
+ updated: true,
2631
+ queryTimeMs: stats.queryTimeMs
2632
+ };
2633
+ },
2634
+ reset() {
2635
+ lastBounds = null;
2636
+ lastData = null;
2637
+ lastStats = null;
2638
+ },
2639
+ getStats() {
2640
+ return lastStats;
2641
+ }
2642
+ };
2643
+ }
2644
+
2645
+ // src/utils/fingerprint.ts
2646
+ function createGeoJSONFingerprint(data) {
2647
+ if (!data) return null;
2648
+ if (typeof data === "string") return null;
2649
+ if (data.type !== "FeatureCollection") return null;
2650
+ const features = data.features;
2651
+ if (!features || !Array.isArray(features)) {
2652
+ return { count: 0, firstId: void 0, lastId: void 0 };
2653
+ }
2654
+ const count = features.length;
2655
+ if (count === 0) {
2656
+ return { count: 0, firstId: void 0, lastId: void 0 };
2657
+ }
2658
+ const firstFeature = features[0];
2659
+ const lastFeature = features[count - 1];
2660
+ return {
2661
+ count,
2662
+ firstId: firstFeature?.id,
2663
+ lastId: lastFeature?.id
2664
+ };
2665
+ }
2666
+ function fingerprintEqual(a, b) {
2667
+ if (a === null && b === null) return true;
2668
+ if (a === null || b === null) return false;
2669
+ return a.count === b.count && a.firstId === b.firstId && a.lastId === b.lastId;
2670
+ }
2671
+ function geoJSONEqual(a, b) {
2672
+ if (typeof a === "string" || typeof b === "string") {
2673
+ return a === b;
2674
+ }
2675
+ if (!a && !b) return true;
2676
+ if (!a || !b) return false;
2677
+ const fpA = createGeoJSONFingerprint(a);
2678
+ const fpB = createGeoJSONFingerprint(b);
2679
+ return fingerprintEqual(fpA, fpB);
2680
+ }
2681
+
2682
+ // src/utils/equality.ts
2683
+ function deepEqual(a, b) {
2684
+ if (a === b) return true;
2685
+ if (a == null || b == null) return a === b;
2686
+ if (typeof a !== typeof b) return false;
2687
+ if (Array.isArray(a) && Array.isArray(b)) {
2688
+ if (a.length !== b.length) return false;
2689
+ for (let i = 0; i < a.length; i++) {
2690
+ if (!deepEqual(a[i], b[i])) return false;
2691
+ }
2692
+ return true;
2693
+ }
2694
+ if (typeof a === "object" && typeof b === "object") {
2695
+ const aKeys = Object.keys(a);
2696
+ const bKeys = Object.keys(b);
2697
+ if (aKeys.length !== bKeys.length) return false;
2698
+ for (const key of aKeys) {
2699
+ if (!Object.prototype.hasOwnProperty.call(b, key) || !deepEqual(a[key], b[key])) {
2700
+ return false;
2701
+ }
2702
+ }
2703
+ return true;
2704
+ }
2705
+ return false;
2706
+ }
2707
+ function paintPropsEqual(prev, next) {
2708
+ if (prev === next) return true;
2709
+ if (!prev && !next) return true;
2710
+ if (!prev || !next) return false;
2711
+ const prevKeys = Object.keys(prev);
2712
+ const nextKeys = Object.keys(next);
2713
+ if (prevKeys.length !== nextKeys.length) return false;
2714
+ for (const key of prevKeys) {
2715
+ if (!Object.prototype.hasOwnProperty.call(next, key)) return false;
2716
+ if (!deepEqual(prev[key], next[key])) return false;
2717
+ }
2718
+ return true;
2719
+ }
2720
+ function getChangedPaintProps(prev, next) {
2721
+ const changed = {};
2722
+ const removed = [];
2723
+ if (!prev) {
2724
+ return {
2725
+ changed: next || {},
2726
+ removed: [],
2727
+ hasChanges: !!next && Object.keys(next).length > 0
2728
+ };
2729
+ }
2730
+ if (!next) {
2731
+ return {
2732
+ changed: {},
2733
+ removed: Object.keys(prev),
2734
+ hasChanges: Object.keys(prev).length > 0
2735
+ };
2736
+ }
2737
+ for (const key of Object.keys(next)) {
2738
+ if (!deepEqual(prev[key], next[key])) {
2739
+ changed[key] = next[key];
2740
+ }
2741
+ }
2742
+ for (const key of Object.keys(prev)) {
2743
+ if (!Object.prototype.hasOwnProperty.call(next, key)) {
2744
+ removed.push(key);
2745
+ }
2746
+ }
2747
+ return {
2748
+ changed,
2749
+ removed,
2750
+ hasChanges: Object.keys(changed).length > 0 || removed.length > 0
2751
+ };
2752
+ }
2753
+ function filterEqual(prev, next) {
2754
+ if (!prev && !next) return true;
2755
+ if (!prev || !next) return false;
2756
+ return deepEqual(prev, next);
2757
+ }
2758
+ function serializeFilter(filter) {
2759
+ if (!filter) return "";
2760
+ try {
2761
+ return JSON.stringify(filter);
2762
+ } catch {
2763
+ return "";
2764
+ }
2765
+ }
2766
+
2767
+ // src/utils/marker.ts
2768
+ var MARKER_PROTECTION_CLASS = "ct-marker-protected";
2769
+ function applyMarkerProtection(element) {
2770
+ element.classList.add(MARKER_PROTECTION_CLASS);
2771
+ const style = element.style;
2772
+ style.setProperty("transition", "none", "important");
2773
+ style.setProperty("transition-property", "none", "important");
2774
+ style.setProperty("animation", "none", "important");
2775
+ style.setProperty("will-change", "transform", "important");
2776
+ }
2777
+ function removeMarkerProtection(element) {
2778
+ element.classList.remove(MARKER_PROTECTION_CLASS);
2779
+ }
2780
+ function applyMarkerChildProtection(element) {
2781
+ const style = element.style;
2782
+ style.setProperty("transition", "none", "important");
2783
+ style.setProperty("animation", "none", "important");
2784
+ }
2785
+
2786
+ // src/utils/popup.ts
2787
+ function normalizePadding(padding) {
2788
+ if (typeof padding === "number") {
2789
+ return { top: padding, right: padding, bottom: padding, left: padding };
2790
+ }
2791
+ return padding;
2792
+ }
2793
+ function prefersReducedMotion() {
2794
+ if (typeof window === "undefined") return false;
2795
+ return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
2796
+ }
2797
+ function panToFitPopup(map, popup, padding) {
2798
+ const popupEl = popup.getElement();
2799
+ if (!popupEl) return;
2800
+ const mapContainer = map.getContainer();
2801
+ const mapRect = mapContainer.getBoundingClientRect();
2802
+ const popupRect = popupEl.getBoundingClientRect();
2803
+ let dx = 0;
2804
+ let dy = 0;
2805
+ if (popupRect.left < mapRect.left + padding.left) {
2806
+ dx = popupRect.left - mapRect.left - padding.left;
2807
+ } else if (popupRect.right > mapRect.right - padding.right) {
2808
+ dx = popupRect.right - mapRect.right + padding.right;
2809
+ }
2810
+ if (popupRect.top < mapRect.top + padding.top) {
2811
+ dy = popupRect.top - mapRect.top - padding.top;
2812
+ } else if (popupRect.bottom > mapRect.bottom - padding.bottom) {
2813
+ dy = popupRect.bottom - mapRect.bottom + padding.bottom;
2814
+ }
2815
+ if (dx !== 0 || dy !== 0) {
2816
+ map.panBy([dx, dy], {
2817
+ animate: !prefersReducedMotion()
2818
+ });
2819
+ }
2820
+ }
2821
+
2822
+ export { DEFAULT_SIMPLIFICATION_THRESHOLDS, KEYBOARD_CONTROLS, MARKER_PROTECTION_CLASS, applyMarkerChildProtection, applyMarkerProtection, boundsToPolygon, buildRTreeIndex, buildSpatialIndex, calculateBounds, calculateCentroid, calculateZoomThresholds, clampLatitude, combineBounds, countFeaturesByType, createCategoricalColorExpression, createCircleStyle, createClusterCirclePaint, createClusterStyles, createClusterTextLayout, createContinuousColorExpression, createDynamicLODManager, createExtrusionHeightExpression, createExtrusionStyle, createFillStyle, createGeoJSONFingerprint, createHeatmapStyle, createHoverExpression, createIdleViewportManager, createInteractiveExpression, createInteractiveStatusColorExpression, createLineStyle, createLotFillStyle, createLotOutlineStyle, createPredictiveViewportManager, createRTreeViewportManager, createSelectionExpression, createStatusColorExpression, createViewportManager, createViewportQuery, createZoomExpression, decimalToDMS, deepEqual, ensureValidCoordinates, expandCluster, expandClusterToBounds, extendBounds, filterByGeometryType, filterEqual, fingerprintEqual, formatArea, formatBearing, formatBounds, formatCoordinates, formatDistance, formatFeatureProperties, formatLabel, formatPitch, formatPropertyValue, formatScale, formatZoom, generateBoundingPolygon, generateConvexHull, generateFeatureCollectionDescription, generateFeatureTable, generateKeyboardControlsDescription, generateLODData, generateLODDataWithSimplification, generateMapDescription, generateMarkerList, generateMarkersDescription, generateMoveAnnouncement, geoJSONEqual, getChangedPaintProps, getClusterBounds, getClusterChildren, getClusterExpansionZoom, getClusterLeaves, getHighlightStyle, getSelectionStyle, getSimplificationToleranceForZoom, getSimplifiedFeaturesForZoom, groupFeaturesByProperty, isClusterFeature, isValidBounds, isValidLatitude, isValidLongitude, loadGeoJSON, normalizeLongitude, normalizePadding, paintPropsEqual, panToFitPopup, prefersReducedMotion, queryByBounds, queryByBoundsWithStats, queryRTreeByBounds, queryRTreeByBoundsWithStats, removeMarkerProtection, serializeFilter, simplifyFeature, simplifyFeatureCollection, simplifyFeatureCollectionWithStats, simplifyPolygon, validateBoundsArray, validateCoordinates, validateGeoJSON, zoomToScale };