@classic-homes/maps-core 0.2.7 → 0.2.9

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