/** * MapLibre GL JS renderer implementation. */ import maplibregl, { Map as MapLibreMap, NavigationControl, ScaleControl, FullscreenControl, GeolocateControl, AttributionControl, Marker, Popup, GlobeControl, } from 'maplibre-gl'; import { MapboxOverlay } from '@deck.gl/mapbox'; import { ArcLayer, PointCloudLayer, ScatterplotLayer, PathLayer, PolygonLayer, IconLayer, TextLayer, GeoJsonLayer, LineLayer, BitmapLayer, ColumnLayer, GridCellLayer, SolidPolygonLayer, } from '@deck.gl/layers'; import { HexagonLayer, HeatmapLayer, GridLayer, ContourLayer, ScreenGridLayer, } from '@deck.gl/aggregation-layers'; import { TripsLayer } from '@deck.gl/geo-layers'; import along from '@turf/along'; import length from '@turf/length'; import { lineString } from '@turf/helpers'; import { proj } from '@developmentseed/deck.gl-geotiff'; import { COGLayerWithOpacity as COGLayer } from './layers/COGLayerWithOpacity'; import { toProj4 } from 'geotiff-geokeys-to-proj4'; import { ZarrLayer } from '@carbonplan/zarr-layer'; import { BaseMapRenderer, MethodHandler } from '../core/BaseMapRenderer'; import { StateManager } from '../core/StateManager'; import type { MapWidgetModel } from '../types/anywidget'; import type { LayerConfig, SourceConfig, ControlPosition, FlyToOptions, FitBoundsOptions, SkySpecification, DEFAULT_PAINT, inferLayerType, } from '../types/maplibre'; import type { Feature, FeatureCollection } from 'geojson'; import { GeoEditorPlugin } from './plugins/GeoEditorPlugin'; import { LayerControlPlugin } from './plugins/LayerControlPlugin'; import { COGLayerAdapter, ZarrLayerAdapter, DeckLayerAdapter, MarkerLayerAdapter } from './adapters'; import { LidarControl, LidarLayerAdapter } from 'maplibre-gl-lidar'; import type { LidarControlOptions, LidarLayerOptions, LidarColorScheme } from '../types/lidar'; import { GeoPhotoControl } from 'maplibre-gl-geophoto'; import { GeoAgentControl, type GeoAgentControlEventHandler, type GeoAgentControlOptions, } from 'maplibre-gl-geoagent'; // Import controls from maplibre-gl-components import { PMTilesLayerControl, CogLayerControl, ZarrLayerControl, AddVectorControl, addControlGrid, Colorbar, SearchControl, MeasureControl, PrintControl, } from 'maplibre-gl-components'; import type { ControlGrid } from 'maplibre-gl-components'; import 'maplibre-gl-components/style.css'; // PMTiles for metadata fetching import { PMTiles } from 'pmtiles'; // FlatGeobuf for streaming cloud-native vector data import { geojson as flatgeobuf } from 'flatgeobuf'; /** * Parse GeoKeys to proj4 definition for COG reprojection. */ async function geoKeysParser( geoKeys: Record, ): Promise { const projDefinition = toProj4(geoKeys as unknown as Parameters[0]); return { def: projDefinition.proj4, parsed: proj.parseCrs(projDefinition.proj4), coordinatesUnits: projDefinition.coordinatesUnits as proj.SupportedCrsUnit, }; } /** * MapLibre GL JS map renderer. */ export class MapLibreRenderer extends BaseMapRenderer { private stateManager: StateManager; private markersMap: globalThis.Map = new globalThis.Map(); private popupsMap: globalThis.Map = new globalThis.Map(); private controlsMap: globalThis.Map = new globalThis.Map(); private legendsMap: globalThis.Map = new globalThis.Map(); private geoEditorPlugin: GeoEditorPlugin | null = null; private layerControlPlugin: LayerControlPlugin | null = null; private resizeObserver: ResizeObserver | null = null; private layerControlOrderSyncTimer: number | null = null; private deckAdaptersRegisteredWithLayerControl = false; // Deck.gl overlay for COG layers protected deckOverlay: MapboxOverlay | null = null; protected deckLayers: globalThis.Map = new globalThis.Map(); // Sentinel layer ID used as ordering anchor for deck.gl layers in interleaved mode. // Deck.gl layers render below this sentinel; native MapLibre layers render above it. protected static readonly DECK_SENTINEL_ID = '__deck-overlay-anchor'; // Track user-added native MapLibre overlay layer IDs (for sentinel positioning) private userOverlayLayerIds: string[] = []; // Zarr layers protected zarrLayers: globalThis.Map = new globalThis.Map(); // Layer control adapters private cogAdapter: COGLayerAdapter | null = null; private zarrAdapter: ZarrLayerAdapter | null = null; private deckLayerAdapter: DeckLayerAdapter | null = null; private lidarAdapter: LidarLayerAdapter | null = null; private markerAdapter: MarkerLayerAdapter | null = null; private markerGroupsMap: globalThis.Map = new globalThis.Map(); // LiDAR control protected lidarControl: LidarControl | null = null; protected lidarLayers: globalThis.Map = new globalThis.Map(); // id -> source mapping // PMTiles sub-layer tracking for auto-discovery removal private pmtilesSubLayers: globalThis.Map = new globalThis.Map(); // PMTiles popup event handler references for cleanup private pmtilesPopupHandlers: globalThis.Map void }>> = new globalThis.Map(); // User-loaded plugin instances private pluginInstances: globalThis.Map = new globalThis.Map(); // maplibre-gl-components controls protected pmtilesLayerControl: PMTilesLayerControl | null = null; protected cogLayerUiControl: CogLayerControl | null = null; protected zarrLayerUiControl: ZarrLayerControl | null = null; protected addVectorControl: AddVectorControl | null = null; protected controlGrid: ControlGrid | null = null; // Colorbar, Search, Measure, Print controls protected colorbarsMap: globalThis.Map = new globalThis.Map(); protected searchControl: SearchControl | null = null; protected measureControl: MeasureControl | null = null; protected printControl: PrintControl | null = null; protected geoPhotoControl: GeoPhotoControl | null = null; protected geoAgentControl: GeoAgentControl | null = null; private geoAgentStateHandler: GeoAgentControlEventHandler | null = null; private geoAgentEventGuardCleanup: (() => void) | null = null; // Route animations protected animations: globalThis.Map = new globalThis.Map(); // Feature hover state tracking protected hoveredFeatureId: string | number | null = null; protected hoveredLayerId: string | null = null; // Video sources tracking (layer id -> source id) protected videoSources: globalThis.Map = new globalThis.Map(); // Split map state private splitMapRight: MapLibreMap | null = null; private splitMapContainer: HTMLDivElement | null = null; private splitSlider: HTMLDivElement | null = null; private splitActive: boolean = false; constructor(model: MapWidgetModel, el: HTMLElement) { super(model, el); this.stateManager = new StateManager(model); this.registerMethods(); } /** * Initialize the MapLibre map. */ async initialize(): Promise { // Create container this.createMapContainer(); // Create map this.map = this.createMap(); // Set up listeners this.setupModelListeners(); this.setupMapEvents(); // Set up resize observer to handle container size changes this.setupResizeObserver(); // Process any JS calls that were made before listeners were set up // These will be queued in pendingCalls since map isn't ready yet this.processJsCalls(); // Wait for map to load await new Promise((resolve) => { this.map!.on('load', () => { this.isMapReady = true; // Restore persisted state (layers, sources) before processing new calls // This ensures layers are restored when map is displayed in subsequent cells this.restoreState(); // Apply initial projection from model trait (must be done after style loads) const initProjection = this.model.get('projection') as string; if (initProjection && initProjection !== 'mercator') { try { this.map!.setProjection({ type: initProjection } as maplibregl.ProjectionSpecification); } catch (err) { console.warn('Failed to set initial projection:', err); } } // Process any calls that were queued while waiting for map to load this.processPendingCalls(); // Resize after load to ensure correct dimensions if (this.map) { this.map.resize(); } resolve(); }); }); } /** * Set up resize observer to handle container size changes. */ private resizeDebounceTimer: number | null = null; private setupResizeObserver(): void { if (!this.mapContainer || !this.map) return; this.resizeObserver = new ResizeObserver(() => { if (this.map) { // Debounce resize to prevent flickering during window resize if (this.resizeDebounceTimer !== null) { window.clearTimeout(this.resizeDebounceTimer); } this.resizeDebounceTimer = window.setTimeout(() => { if (this.map) { this.map.resize(); } this.resizeDebounceTimer = null; }, 100); } }); this.resizeObserver.observe(this.mapContainer); // Also observe the parent element this.resizeObserver.observe(this.el); } /** * Create the MapLibre map instance. */ protected createMap(): MapLibreMap { const style = this.model.get('style'); const center = this.model.get('center'); const zoom = this.model.get('zoom'); const bearing = this.model.get('bearing') || 0; const pitch = this.model.get('pitch') || 0; const maxPitchValue = this.model.get('max_pitch'); const maxPitch = typeof maxPitchValue === 'number' ? maxPitchValue : 85; const maxZoomValue = this.model.get('max_zoom'); const maxZoom = typeof maxZoomValue === 'number' ? maxZoomValue : 25.5; return new MapLibreMap({ container: this.mapContainer!, style: typeof style === 'string' ? style : (style as maplibregl.StyleSpecification), center: center as [number, number], zoom, bearing, pitch, maxPitch, maxZoom, attributionControl: false, }); } /** * Set up map event listeners. */ private setupMapEvents(): void { if (!this.map) return; // Click event this.map.on('click', (e) => { this.model.set('clicked', { lng: e.lngLat.lng, lat: e.lngLat.lat, point: [e.point.x, e.point.y], }); this.sendEvent('click', { lngLat: [e.lngLat.lng, e.lngLat.lat], point: [e.point.x, e.point.y], }); this.model.save_changes(); }); // Move end event this.map.on('moveend', () => { if (!this.map) return; const center = this.map.getCenter(); const bounds = this.map.getBounds(); const zoom = this.map.getZoom(); if (bounds) { this.model.set('current_center', [center.lng, center.lat]); this.model.set('current_zoom', zoom); this.model.set('current_bounds', [ bounds.getWest(), bounds.getSouth(), bounds.getEast(), bounds.getNorth(), ]); this.model.save_changes(); this.sendEvent('moveend', { center: [center.lng, center.lat], zoom, bounds: [ bounds.getWest(), bounds.getSouth(), bounds.getEast(), bounds.getNorth(), ], }); } }); // Zoom end event this.map.on('zoomend', () => { if (!this.map) return; this.sendEvent('zoomend', { zoom: this.map.getZoom() }); }); } /** * Register all method handlers. */ private registerMethods(): void { // Map navigation this.registerMethod('setCenter', this.handleSetCenter.bind(this)); this.registerMethod('setZoom', this.handleSetZoom.bind(this)); this.registerMethod('flyTo', this.handleFlyTo.bind(this)); this.registerMethod('fitBounds', this.handleFitBounds.bind(this)); // Sources this.registerMethod('addSource', this.handleAddSource.bind(this)); this.registerMethod('removeSource', this.handleRemoveSource.bind(this)); // Layers this.registerMethod('addLayer', this.handleAddLayer.bind(this)); this.registerMethod('removeLayer', this.handleRemoveLayer.bind(this)); this.registerMethod('setVisibility', this.handleSetVisibility.bind(this)); this.registerMethod('setOpacity', this.handleSetOpacity.bind(this)); this.registerMethod('setPaintProperty', this.handleSetPaintProperty.bind(this)); this.registerMethod('setLayoutProperty', this.handleSetLayoutProperty.bind(this)); // Basemaps this.registerMethod('addBasemap', this.handleAddBasemap.bind(this)); // Vector data this.registerMethod('addGeoJSON', this.handleAddGeoJSON.bind(this)); // Raster data this.registerMethod('addTileLayer', this.handleAddTileLayer.bind(this)); this.registerMethod('addImageLayer', this.handleAddImageLayer.bind(this)); // Controls this.registerMethod('addControl', this.handleAddControl.bind(this)); this.registerMethod('removeControl', this.handleRemoveControl.bind(this)); this.registerMethod('addLayerControl', this.handleAddLayerControl.bind(this)); // Draw control this.registerMethod('addDrawControl', this.handleAddDrawControl.bind(this)); this.registerMethod('getDrawData', this.handleGetDrawData.bind(this)); this.registerMethod('loadDrawData', this.handleLoadDrawData.bind(this)); this.registerMethod('clearDrawData', this.handleClearDrawData.bind(this)); // Markers and popups this.registerMethod('addMarker', this.handleAddMarker.bind(this)); this.registerMethod('addMarkers', this.handleAddMarkers.bind(this)); this.registerMethod('removeMarker', this.handleRemoveMarker.bind(this)); this.registerMethod('addPopup', this.handleAddPopup.bind(this)); // Legend this.registerMethod('addLegend', this.handleAddLegend.bind(this)); this.registerMethod('removeLegend', this.handleRemoveLegend.bind(this)); // Terrain this.registerMethod('addTerrain', this.handleAddTerrain.bind(this)); // Layer management (moveLayer is new, setPaintProperty/setLayoutProperty already registered) this.registerMethod('moveLayer', this.handleMoveLayer.bind(this)); // COG layers (deck.gl) this.registerMethod('addCOGLayer', this.handleAddCOGLayer.bind(this)); this.registerMethod('removeCOGLayer', this.handleRemoveCOGLayer.bind(this)); // Zarr layers (@carbonplan/zarr-layer) this.registerMethod('addZarrLayer', this.handleAddZarrLayer.bind(this)); this.registerMethod('removeZarrLayer', this.handleRemoveZarrLayer.bind(this)); this.registerMethod('updateZarrLayer', this.handleUpdateZarrLayer.bind(this)); // Arc layers (deck.gl) this.registerMethod('addArcLayer', this.handleAddArcLayer.bind(this)); this.registerMethod('removeArcLayer', this.handleRemoveArcLayer.bind(this)); // PointCloud layers (deck.gl) this.registerMethod('addPointCloudLayer', this.handleAddPointCloudLayer.bind(this)); this.registerMethod('removePointCloudLayer', this.handleRemovePointCloudLayer.bind(this)); // Additional deck.gl layers this.registerMethod('addScatterplotLayer', this.handleAddScatterplotLayer.bind(this)); this.registerMethod('addPathLayer', this.handleAddPathLayer.bind(this)); this.registerMethod('addPolygonLayer', this.handleAddPolygonLayer.bind(this)); this.registerMethod('addHexagonLayer', this.handleAddHexagonLayer.bind(this)); this.registerMethod('addHeatmapLayer', this.handleAddHeatmapLayer.bind(this)); this.registerMethod('addGridLayer', this.handleAddGridLayer.bind(this)); this.registerMethod('addIconLayer', this.handleAddIconLayer.bind(this)); this.registerMethod('addTextLayer', this.handleAddTextLayer.bind(this)); this.registerMethod('addGeoJsonLayer', this.handleAddGeoJsonLayer.bind(this)); this.registerMethod('addContourLayer', this.handleAddContourLayer.bind(this)); this.registerMethod('addScreenGridLayer', this.handleAddScreenGridLayer.bind(this)); this.registerMethod('addTripsLayer', this.handleAddTripsLayer.bind(this)); this.registerMethod('addLineLayer', this.handleAddLineLayer.bind(this)); this.registerMethod('addDeckGLLayer', this.handleAddDeckGLLayer.bind(this)); this.registerMethod('removeDeckLayer', this.handleRemoveDeckLayer.bind(this)); this.registerMethod('setDeckLayerVisibility', this.handleSetDeckLayerVisibility.bind(this)); // Additional deck.gl layers this.registerMethod('addBitmapLayer', this.handleAddBitmapLayer.bind(this)); this.registerMethod('addColumnLayer', this.handleAddColumnLayer.bind(this)); this.registerMethod('addGridCellLayer', this.handleAddGridCellLayer.bind(this)); this.registerMethod('addSolidPolygonLayer', this.handleAddSolidPolygonLayer.bind(this)); // Note: Heavy geo-layers (MVT, Tile3D, Terrain, H3, S2, etc.) and mesh-layers // (SimpleMesh, Scenegraph) are only available in DeckGLRenderer to keep the // maplibre.js bundle lightweight. // Native MapLibre features this.registerMethod('setProjection', this.handleSetProjection.bind(this)); this.registerMethod('updateGeoJSONSource', this.handleUpdateGeoJSONSource.bind(this)); this.registerMethod('addMapImage', this.handleAddMapImage.bind(this)); this.registerMethod('addTooltip', this.handleAddTooltip.bind(this)); this.registerMethod('removeTooltip', this.handleRemoveTooltip.bind(this)); this.registerMethod('addCoordinatesControl', this.handleAddCoordinatesControl.bind(this)); this.registerMethod('removeCoordinatesControl', this.handleRemoveCoordinatesControl.bind(this)); // Time slider this.registerMethod('addTimeSlider', this.handleAddTimeSlider.bind(this)); this.registerMethod('removeTimeSlider', this.handleRemoveTimeSlider.bind(this)); // UI enhancements this.registerMethod('addSwipeMap', this.handleAddSwipeMap.bind(this)); this.registerMethod('removeSwipeMap', this.handleRemoveSwipeMap.bind(this)); this.registerMethod('addOpacitySlider', this.handleAddOpacitySlider.bind(this)); this.registerMethod('removeOpacitySlider', this.handleRemoveOpacitySlider.bind(this)); this.registerMethod('addStyleSwitcher', this.handleAddStyleSwitcher.bind(this)); this.registerMethod('removeStyleSwitcher', this.handleRemoveStyleSwitcher.bind(this)); // Data export this.registerMethod('getVisibleFeatures', this.handleGetVisibleFeatures.bind(this)); this.registerMethod('getLayerData', this.handleGetLayerData.bind(this)); // LiDAR layers (maplibre-gl-lidar) this.registerMethod('addLidarControl', this.handleAddLidarControl.bind(this)); this.registerMethod('addLidarLayer', this.handleAddLidarLayer.bind(this)); this.registerMethod('removeLidarLayer', this.handleRemoveLidarLayer.bind(this)); this.registerMethod('setLidarColorScheme', this.handleSetLidarColorScheme.bind(this)); this.registerMethod('setLidarPointSize', this.handleSetLidarPointSize.bind(this)); this.registerMethod('setLidarOpacity', this.handleSetLidarOpacity.bind(this)); // PMTiles layers this.registerMethod('addPMTilesLayer', this.handleAddPMTilesLayer.bind(this)); this.registerMethod('removePMTilesLayer', this.handleRemovePMTilesLayer.bind(this)); // maplibre-gl-components controls this.registerMethod('addPMTilesControl', this.handleAddPMTilesControl.bind(this)); this.registerMethod('addCogControl', this.handleAddCogControl.bind(this)); this.registerMethod('addZarrControl', this.handleAddZarrControl.bind(this)); this.registerMethod('addVectorControl', this.handleAddVectorControl.bind(this)); this.registerMethod('addControlGrid', this.handleAddControlGrid.bind(this)); // Clustering this.registerMethod('addClusterLayer', this.handleAddClusterLayer.bind(this)); this.registerMethod('removeClusterLayer', this.handleRemoveClusterLayer.bind(this)); // Choropleth this.registerMethod('addChoropleth', this.handleAddChoropleth.bind(this)); // 3D Buildings this.registerMethod('add3DBuildings', this.handleAdd3DBuildings.bind(this)); // Route Animation this.registerMethod('animateAlongRoute', this.handleAnimateAlongRoute.bind(this)); this.registerMethod('stopAnimation', this.handleStopAnimation.bind(this)); this.registerMethod('pauseAnimation', this.handlePauseAnimation.bind(this)); this.registerMethod('resumeAnimation', this.handleResumeAnimation.bind(this)); this.registerMethod('setAnimationSpeed', this.handleSetAnimationSpeed.bind(this)); // Feature Hover this.registerMethod('addHoverEffect', this.handleAddHoverEffect.bind(this)); // Sky & Fog this.registerMethod('setSky', this.handleSetSky.bind(this)); this.registerMethod('removeSky', this.handleRemoveSky.bind(this)); // Feature Query/Filter this.registerMethod('setFilter', this.handleSetFilter.bind(this)); this.registerMethod('queryRenderedFeatures', this.handleQueryRenderedFeatures.bind(this)); this.registerMethod('querySourceFeatures', this.handleQuerySourceFeatures.bind(this)); // Video Layer this.registerMethod('addVideoLayer', this.handleAddVideoLayer.bind(this)); this.registerMethod('removeVideoLayer', this.handleRemoveVideoLayer.bind(this)); this.registerMethod('playVideo', this.handlePlayVideo.bind(this)); this.registerMethod('pauseVideo', this.handlePauseVideo.bind(this)); this.registerMethod('seekVideo', this.handleSeekVideo.bind(this)); // Split Map this.registerMethod('addSplitMap', this.handleAddSplitMap.bind(this)); this.registerMethod('removeSplitMap', this.handleRemoveSplitMap.bind(this)); // Colorbar this.registerMethod('addColorbar', this.handleAddColorbar.bind(this)); this.registerMethod('removeColorbar', this.handleRemoveColorbar.bind(this)); this.registerMethod('updateColorbar', this.handleUpdateColorbar.bind(this)); // Search Control this.registerMethod('addSearchControl', this.handleAddSearchControl.bind(this)); this.registerMethod('removeSearchControl', this.handleRemoveSearchControl.bind(this)); // Measure Control this.registerMethod('addMeasureControl', this.handleAddMeasureControl.bind(this)); this.registerMethod('removeMeasureControl', this.handleRemoveMeasureControl.bind(this)); // Print Control this.registerMethod('addPrintControl', this.handleAddPrintControl.bind(this)); this.registerMethod('removePrintControl', this.handleRemovePrintControl.bind(this)); // GeoPhoto Control this.registerMethod('addGeoPhotoControl', this.handleAddGeoPhotoControl.bind(this)); this.registerMethod('removeGeoPhotoControl', this.handleRemoveGeoPhotoControl.bind(this)); // GeoAgent control this.registerMethod('addGeoAgentControl', this.handleAddGeoAgentControl.bind(this)); this.registerMethod('removeGeoAgentControl', this.handleRemoveGeoAgentControl.bind(this)); this.registerMethod('setGeoAgentState', this.handleSetGeoAgentState.bind(this)); this.registerMethod('loadGeoPhotoZip', this.handleLoadGeoPhotoZip.bind(this)); this.registerMethod('loadGeoPhotoUrls', this.handleLoadGeoPhotoUrls.bind(this)); this.registerMethod('geoPhotoSelectCamera', this.handleGeoPhotoSelectCamera.bind(this)); this.registerMethod('geoPhotoNextCamera', this.handleGeoPhotoNextCamera.bind(this)); this.registerMethod('geoPhotoPrevCamera', this.handleGeoPhotoPrevCamera.bind(this)); this.registerMethod('geoPhotoPlay', this.handleGeoPhotoPlay.bind(this)); this.registerMethod('geoPhotoStop', this.handleGeoPhotoStop.bind(this)); this.registerMethod('geoPhotoClearData', this.handleGeoPhotoClearData.bind(this)); // FlatGeobuf this.registerMethod('addFlatGeobuf', this.handleAddFlatGeobuf.bind(this)); this.registerMethod('removeFlatGeobuf', this.handleRemoveFlatGeobuf.bind(this)); // Private plugins this.registerMethod('loadPlugin', this.handleLoadPlugin.bind(this)); this.registerMethod('removePlugin', this.handleRemovePlugin.bind(this)); this.registerMethod('callPluginMethod', this.handleCallPluginMethod.bind(this)); } // ------------------------------------------------------------------------- // Map navigation handlers // ------------------------------------------------------------------------- private handleSetCenter(args: unknown[], kwargs: Record): void { if (!this.map) return; const [lng, lat] = args as [number, number]; this.map.setCenter([lng, lat]); } private handleSetZoom(args: unknown[], kwargs: Record): void { if (!this.map) return; const [zoom] = args as [number]; this.map.setZoom(zoom); } private handleFlyTo(args: unknown[], kwargs: Record): void { if (!this.map) return; const [lng, lat] = args as [number, number]; const options: FlyToOptions = { center: [lng, lat], zoom: kwargs.zoom as number | undefined, bearing: kwargs.bearing as number | undefined, pitch: kwargs.pitch as number | undefined, duration: (kwargs.duration as number) || 2000, }; this.map.flyTo(options); } private handleFitBounds(args: unknown[], kwargs: Record): void { if (!this.map) return; const [bounds] = args as [[number, number, number, number]]; const options: FitBoundsOptions = { padding: (kwargs.padding as number) || 50, duration: (kwargs.duration as number) || 1000, maxZoom: kwargs.maxZoom as number | undefined, }; this.map.fitBounds( [ [bounds[0], bounds[1]], [bounds[2], bounds[3]], ], options ); } // ------------------------------------------------------------------------- // Source handlers // ------------------------------------------------------------------------- private handleAddSource(args: unknown[], kwargs: Record): void { if (!this.map) return; const [sourceId] = args as [string]; const config = kwargs as unknown as SourceConfig; if (this.map.getSource(sourceId)) { console.warn(`Source ${sourceId} already exists`); return; } this.map.addSource(sourceId, config as maplibregl.SourceSpecification); this.stateManager.addSource(sourceId, config); } private handleRemoveSource(args: unknown[], kwargs: Record): void { if (!this.map) return; const [sourceId] = args as [string]; if (!this.map.getSource(sourceId)) { return; } this.map.removeSource(sourceId); this.stateManager.removeSource(sourceId); } // ------------------------------------------------------------------------- // Layer handlers // ------------------------------------------------------------------------- private handleAddLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; const config = kwargs as unknown as LayerConfig; if (this.map.getLayer(config.id)) { console.warn(`Layer ${config.id} already exists`); return; } // Skip if the referenced source doesn't exist yet (it will be created // when the original addGeoJSON / addFlatGeobuf call is replayed) const sourceId = (config as unknown as Record).source as string | undefined; if (sourceId && typeof sourceId === 'string' && !this.map.getSource(sourceId)) { return; } const beforeId = kwargs.beforeId as string | undefined; this.map.addLayer(config as maplibregl.LayerSpecification, beforeId); this.stateManager.addLayer(config.id, config); } private handleRemoveLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; const [layerId] = args as [string]; if (!this.map.getLayer(layerId)) { return; } this.map.removeLayer(layerId); this.stateManager.removeLayer(layerId); } private handleSetVisibility(args: unknown[], kwargs: Record): void { if (!this.map) return; const [layerId, visible] = args as [string, boolean]; if (!this.map.getLayer(layerId)) { return; } this.map.setLayoutProperty(layerId, 'visibility', visible ? 'visible' : 'none'); this.stateManager.setLayerVisibility(layerId, visible); } private handleSetOpacity(args: unknown[], kwargs: Record): void { if (!this.map) return; const [layerId, opacity] = args as [string, number]; if (!this.map.getLayer(layerId)) { return; } const layer = this.map.getLayer(layerId); if (!layer) return; // Set opacity based on layer type const type = layer.type; const opacityProperty = this.getOpacityProperty(type); if (opacityProperty) { this.map.setPaintProperty(layerId, opacityProperty, opacity); } this.stateManager.setLayerOpacity(layerId, opacity); } private getOpacityProperty(layerType: string): string | null { const opacityMap: Record = { fill: 'fill-opacity', line: 'line-opacity', circle: 'circle-opacity', symbol: 'icon-opacity', raster: 'raster-opacity', 'fill-extrusion': 'fill-extrusion-opacity', heatmap: 'heatmap-opacity', }; return opacityMap[layerType] || null; } private handleSetPaintProperty(args: unknown[], kwargs: Record): void { if (!this.map) return; const [layerId, property, value] = args as [string, string, unknown]; if (!this.map.getLayer(layerId)) { return; } this.map.setPaintProperty(layerId, property, value); } private handleSetLayoutProperty(args: unknown[], kwargs: Record): void { if (!this.map) return; const [layerId, property, value] = args as [string, string, unknown]; if (!this.map.getLayer(layerId)) { return; } this.map.setLayoutProperty(layerId, property, value); } // ------------------------------------------------------------------------- // Basemap handlers // ------------------------------------------------------------------------- private handleAddBasemap(args: unknown[], kwargs: Record): void { if (!this.map) return; const [url] = args as [string]; const name = (kwargs.name as string) || 'basemap'; const attribution = (kwargs.attribution as string) || ''; const beforeId = kwargs.beforeId as string | undefined; const sourceId = `basemap-${name}`; const layerId = `${name}`; // Add source if not exists if (!this.map.getSource(sourceId)) { const sourceConfig = { type: 'raster' as const, tiles: [url], tileSize: 256, attribution, }; this.map.addSource(sourceId, sourceConfig); // Persist source state for multi-cell rendering this.stateManager.addSource(sourceId, sourceConfig as unknown as SourceConfig); } // Add layer, optionally before a specified layer. // If the deck.gl sentinel exists and no explicit beforeId, insert the // basemap below the sentinel so it renders under deck.gl layers. if (!this.map.getLayer(layerId)) { const layerConfig = { id: layerId, type: 'raster' as const, source: sourceId, }; // Insert basemap above background layers but below the deck sentinel // and user overlay layers, so it doesn't cover deck.gl content and // doesn't get hidden beneath the style's background layer. let effectiveBeforeId = beforeId; if (!effectiveBeforeId) { const sentinel = MapLibreRenderer.DECK_SENTINEL_ID; if (this.map.getLayer(sentinel)) { // Find first deck.gl proxy layer (inserted before sentinel) so the // basemap sits below all deck.gl layers. If none exist yet the // basemap goes right before the sentinel which is still correct. const styleLayers = this.map.getStyle()?.layers || []; const sentinelIdx = styleLayers.findIndex(l => l.id === sentinel); // Walk backwards from sentinel to find start of deck.gl block let insertIdx = sentinelIdx; for (let i = sentinelIdx - 1; i >= 0; i--) { if (styleLayers[i].id.startsWith('@@deck.gl')) { insertIdx = i; } else { break; } } effectiveBeforeId = styleLayers[insertIdx]?.id; } } this.map.addLayer(layerConfig, effectiveBeforeId); // Persist layer state for multi-cell rendering this.stateManager.addLayer(layerId, layerConfig as unknown as LayerConfig); } } // ------------------------------------------------------------------------- // Vector data handlers // ------------------------------------------------------------------------- private handleAddGeoJSON(args: unknown[], kwargs: Record): void { if (!this.map) return; const geojson = kwargs.data as FeatureCollection | Feature; const name = kwargs.name as string; const layerType = kwargs.layerType as string; const paint = kwargs.paint as Record | undefined; const fitBounds = kwargs.fitBounds !== false; const sourceId = `${name}-source`; const layerId = name; // Determine layer type from geometry if not specified let type = layerType; if (!type && geojson.type === 'FeatureCollection' && geojson.features.length > 0) { const geometry = geojson.features[0].geometry; type = this.inferLayerType(geometry.type); } else if (!type && geojson.type === 'Feature') { type = this.inferLayerType(geojson.geometry.type); } type = type || 'circle'; // Get default paint if not provided const defaultPaint = this.getDefaultPaint(type); const layerPaint = paint || defaultPaint; // Add source if (!this.map.getSource(sourceId)) { const sourceConfig = { type: 'geojson' as const, data: geojson, }; this.map.addSource(sourceId, sourceConfig); // Persist source state for multi-cell rendering this.stateManager.addSource(sourceId, sourceConfig as unknown as SourceConfig); } // Add layer if (!this.map.getLayer(layerId)) { const layerConfig = { id: layerId, type: type as maplibregl.LayerSpecification['type'], source: sourceId, paint: layerPaint, }; this.map.addLayer(layerConfig as maplibregl.AddLayerObject); // Persist layer state for multi-cell rendering this.stateManager.addLayer(layerId, layerConfig as unknown as LayerConfig); // Track as user overlay layer for deck.gl ordering this.userOverlayLayerIds.push(layerId); } // Fit bounds if (fitBounds && kwargs.bounds) { const bounds = kwargs.bounds as [number, number, number, number]; this.map.fitBounds( [ [bounds[0], bounds[1]], [bounds[2], bounds[3]], ], { padding: 50 } ); } } private inferLayerType(geometryType: string): string { switch (geometryType) { case 'Point': case 'MultiPoint': return 'circle'; case 'LineString': case 'MultiLineString': return 'line'; case 'Polygon': case 'MultiPolygon': return 'fill'; default: return 'circle'; } } private getDefaultPaint(layerType: string): Record { const defaults: Record> = { circle: { 'circle-radius': 5, 'circle-color': '#3388ff', 'circle-opacity': 0.8, 'circle-stroke-width': 1, 'circle-stroke-color': '#ffffff', }, line: { 'line-color': '#3388ff', 'line-width': 2, 'line-opacity': 0.8, }, fill: { 'fill-color': '#3388ff', 'fill-opacity': 0.5, 'fill-outline-color': '#0000ff', }, raster: { 'raster-opacity': 1, }, }; return defaults[layerType] || {}; } // ------------------------------------------------------------------------- // Raster data handlers // ------------------------------------------------------------------------- private handleAddTileLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; const [url] = args as [string]; const name = (kwargs.name as string) || `tiles-${Date.now()}`; const attribution = (kwargs.attribution as string) || ''; const minZoom = (kwargs.minZoom as number) || 0; const maxZoom = (kwargs.maxZoom as number) || 22; const sourceId = `${name}-source`; const layerId = name; // Add source if (!this.map.getSource(sourceId)) { const sourceConfig = { type: 'raster' as const, tiles: [url], tileSize: 256, attribution, minzoom: minZoom, maxzoom: maxZoom, }; this.map.addSource(sourceId, sourceConfig); // Persist source state for multi-cell rendering this.stateManager.addSource(sourceId, sourceConfig as unknown as SourceConfig); } // Add layer if (!this.map.getLayer(layerId)) { const layerConfig = { id: layerId, type: 'raster' as const, source: sourceId, minzoom: minZoom, maxzoom: maxZoom, }; this.map.addLayer(layerConfig); // Persist layer state for multi-cell rendering this.stateManager.addLayer(layerId, layerConfig as unknown as LayerConfig); } } private handleAddImageLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; const id = (kwargs.id as string) || `image-${Date.now()}`; const url = kwargs.url as string; const coordinates = kwargs.coordinates as number[][]; const opacity = (kwargs.opacity as number) ?? 1.0; if (!url || !coordinates || coordinates.length !== 4) { console.error('addImageLayer requires url and 4 corner coordinates'); return; } const sourceId = `${id}-source`; // Add image source if (!this.map.getSource(sourceId)) { this.map.addSource(sourceId, { type: 'image', url: url, coordinates: coordinates as [[number, number], [number, number], [number, number], [number, number]], }); } // Add raster layer if (!this.map.getLayer(id)) { this.map.addLayer({ id: id, type: 'raster', source: sourceId, paint: { 'raster-opacity': opacity, }, }); } } // ------------------------------------------------------------------------- // Control handlers // ------------------------------------------------------------------------- private handleAddControl(args: unknown[], kwargs: Record): void { if (!this.map) return; const [controlType] = args as [string]; const position = (kwargs.position as ControlPosition) || 'top-right'; let control: maplibregl.IControl | null = null; switch (controlType) { case 'navigation': control = new NavigationControl({ showCompass: kwargs.showCompass !== false, showZoom: kwargs.showZoom !== false, visualizePitch: kwargs.visualizePitch !== false, }); break; case 'scale': control = new ScaleControl({ maxWidth: (kwargs.maxWidth as number) || 100, unit: (kwargs.unit as 'imperial' | 'metric' | 'nautical') || 'metric', }); break; case 'fullscreen': control = new FullscreenControl(); break; case 'geolocate': control = new GeolocateControl({ positionOptions: { enableHighAccuracy: true }, trackUserLocation: kwargs.trackUserLocation !== false, }); break; case 'attribution': control = new AttributionControl({ compact: kwargs.compact !== false, }); break; case 'globe': control = new GlobeControl(); break; case 'geoagent': case 'geoagent-control': this.handleAddGeoAgentControl(args, kwargs); return; } if (control) { this.map.addControl(control, position); this.controlsMap.set(controlType, control); this.stateManager.addControl(controlType, controlType, position, kwargs); } } private handleRemoveControl(args: unknown[], kwargs: Record): void { if (!this.map) return; const [controlType] = args as [string]; if (controlType === 'geoagent' || controlType === 'geoagent-control') { this.handleRemoveGeoAgentControl(args, kwargs); return; } const control = this.controlsMap.get(controlType); if (control) { this.map.removeControl(control); this.controlsMap.delete(controlType); this.stateManager.removeControl(controlType); } } private handleAddLayerControl(args: unknown[], kwargs: Record): void { if (!this.map) return; // Get layers from kwargs, or fall back to restored layers from model let layers = kwargs.layers as string[] | undefined; if (!layers || layers.length === 0) { const modelLayers = this.model.get('_layers') || {}; const layerIds = Object.keys(modelLayers); if (layerIds.length > 0) { layers = layerIds; } } const position = (kwargs.position as ControlPosition) || 'top-right'; const collapsed = (kwargs.collapsed as boolean) || false; // Exclude internal/helper layers from the layer control by default const defaultExclude = [ 'measure-*', 'mapbox-gl-draw-*', 'gl-draw-*', 'gm_*', 'inspect-highlight-*', 'lidar-*', 'usgs-lidar-*', MapLibreRenderer.DECK_SENTINEL_ID, ]; const excludeLayers = (kwargs.excludeLayers as string[] | undefined) ?? defaultExclude; // Create custom layer adapters for deck.gl and Zarr layers const customLayerAdapters = []; // Only wire deck.gl adapters when a deck overlay already exists. // Eagerly creating an interleaved deck overlay here breaks native terrain. if (this.deckOverlay && this.map) { if (!this.cogAdapter) { this.cogAdapter = new COGLayerAdapter(this.map, this.deckOverlay, this.deckLayers); } customLayerAdapters.push(this.cogAdapter); } // Create Zarr adapter if there are Zarr layers or map exists if (this.map) { this.zarrAdapter = new ZarrLayerAdapter(this.map, this.zarrLayers); customLayerAdapters.push(this.zarrAdapter); } // Create Deck layer adapter for Arc and PointCloud layers if (this.deckOverlay && this.map) { if (!this.deckLayerAdapter) { this.deckLayerAdapter = new DeckLayerAdapter(this.map, this.deckOverlay, this.deckLayers); } customLayerAdapters.push(this.deckLayerAdapter); } // Create LiDAR adapter if LidarControl exists if (this.lidarControl) { this.lidarAdapter = new LidarLayerAdapter(this.lidarControl); customLayerAdapters.push(this.lidarAdapter); } // Create Marker adapter for DOM-based markers if (this.map) { this.markerAdapter = new MarkerLayerAdapter(this.map); // Register any marker groups added before the layer control this.markerGroupsMap.forEach((markers, groupId) => { this.markerAdapter!.addMarkerGroup(groupId, groupId, markers); }); customLayerAdapters.push(this.markerAdapter); } // Initialize plugin if not already if (!this.layerControlPlugin) { this.layerControlPlugin = new LayerControlPlugin(this.map); } this.deckAdaptersRegisteredWithLayerControl = this.deckOverlay !== null && this.map !== null; this.layerControlPlugin.initialize({ layers, position, collapsed, customLayerAdapters: customLayerAdapters.length > 0 ? customLayerAdapters : undefined, excludeLayers, resolveLayerOrder: this.getLayerControlOrder.bind(this), onLayerReorder: this.handleLayerControlReorder.bind(this), }); this.stateManager.addControl('layer-control', 'layer-control', position, kwargs); } // ------------------------------------------------------------------------- // Draw control handlers // ------------------------------------------------------------------------- private handleAddDrawControl(args: unknown[], kwargs: Record): void { if (!this.map) return; const position = (kwargs.position as ControlPosition) || 'top-right'; const drawModes = kwargs.drawModes as string[] | undefined; const editModes = kwargs.editModes as string[] | undefined; const collapsed = (kwargs.collapsed as boolean) || false; // Initialize plugin if not already if (!this.geoEditorPlugin) { this.geoEditorPlugin = new GeoEditorPlugin(this.map); } this.geoEditorPlugin.initialize( { position, drawModes, editModes, collapsed, }, (data: FeatureCollection) => { // Sync draw data to Python this.model.set('_draw_data', data); this.model.save_changes(); } ); this.stateManager.addControl('draw-control', 'draw-control', position, kwargs); } private handleGetDrawData(args: unknown[], kwargs: Record): void { if (!this.geoEditorPlugin) { this.model.set('_draw_data', { type: 'FeatureCollection', features: [] }); this.model.save_changes(); return; } const data = this.geoEditorPlugin.getFeatures(); this.model.set('_draw_data', data); this.model.save_changes(); } private handleLoadDrawData(args: unknown[], kwargs: Record): void { if (!this.geoEditorPlugin) { console.warn('Draw control not initialized'); return; } const geojson = args[0] as FeatureCollection; this.geoEditorPlugin.loadFeatures(geojson); } private handleClearDrawData(args: unknown[], kwargs: Record): void { if (!this.geoEditorPlugin) { return; } this.geoEditorPlugin.clear(); this.model.set('_draw_data', { type: 'FeatureCollection', features: [] }); this.model.save_changes(); } // ------------------------------------------------------------------------- // Marker handlers // ------------------------------------------------------------------------- // Helper to wrap popup/tooltip content with contrast-safe styling private wrapWithContrastStyle(content: string): string { return `
${content}
`; } private handleAddMarker(args: unknown[], kwargs: Record): void { if (!this.map) return; const [lng, lat] = args as [number, number]; const id = (kwargs.id as string) || `marker-${Date.now()}`; const color = (kwargs.color as string) || '#3388ff'; const popup = kwargs.popup as string | undefined; const tooltip = kwargs.tooltip as string | undefined; const scale = (kwargs.scale as number) ?? 1.0; const popupMaxWidth = (kwargs.popupMaxWidth as string) || '240px'; const tooltipMaxWidth = (kwargs.tooltipMaxWidth as string) || '240px'; const draggable = (kwargs.draggable as boolean) || false; const marker = new Marker({ color, scale, draggable }).setLngLat([lng, lat]); if (popup) { marker.setPopup(new Popup({ maxWidth: popupMaxWidth }).setHTML(this.wrapWithContrastStyle(popup))); } // Add tooltip (shown on hover) if (tooltip) { const tooltipPopup = new Popup({ closeButton: false, closeOnClick: false, maxWidth: tooltipMaxWidth, offset: [0, -30 * scale], // Offset above the marker based on scale anchor: 'bottom', }); tooltipPopup.setHTML(this.wrapWithContrastStyle(tooltip)); const markerElement = marker.getElement(); let isHovering = false; markerElement.addEventListener('mouseenter', () => { isHovering = true; tooltipPopup.setLngLat([lng, lat]).addTo(this.map!); }); markerElement.addEventListener('mouseleave', (e: MouseEvent) => { // Check if we're moving to the popup itself const relatedTarget = e.relatedTarget as HTMLElement; if (relatedTarget?.closest('.maplibregl-popup')) { return; } isHovering = false; tooltipPopup.remove(); }); // Also handle leaving the popup tooltipPopup.on('close', () => { isHovering = false; }); } marker.addTo(this.map); this.markersMap.set(id, marker); this.markerGroupsMap.set(id, [marker]); if (this.markerAdapter) { this.markerAdapter.addMarkerGroup(id, id, [marker]); } } private handleRemoveMarker(args: unknown[], kwargs: Record): void { const [id] = args as [string]; // Remove via group tracking (handles both single markers and marker groups) const group = this.markerGroupsMap.get(id); if (group) { for (const m of group) { m.remove(); } this.markerGroupsMap.delete(id); // Clean up individual entries from markersMap if (this.markersMap.has(id)) { this.markersMap.delete(id); } else { const prefix = `${id}-`; const toDelete: string[] = []; this.markersMap.forEach((_, key) => { if (key.startsWith(prefix)) toDelete.push(key); }); toDelete.forEach(key => this.markersMap.delete(key)); } } else { // Fallback: direct marker lookup const marker = this.markersMap.get(id); if (marker) { marker.remove(); this.markersMap.delete(id); } } if (this.markerAdapter) { this.markerAdapter.removeMarkerGroup(id); } } private handleAddMarkers(args: unknown[], kwargs: Record): void { if (!this.map) return; const id = (kwargs.id as string) || `markers-${Date.now()}`; const markers = kwargs.markers as Array<{ lngLat: [number, number]; popup?: string; tooltip?: string; scale?: number; popupMaxWidth?: string; tooltipMaxWidth?: string; }>; const color = (kwargs.color as string) || '#3388ff'; const defaultScale = (kwargs.scale as number) ?? 1.0; const defaultPopupMaxWidth = (kwargs.popupMaxWidth as string) || '240px'; const defaultTooltipMaxWidth = (kwargs.tooltipMaxWidth as string) || '240px'; const draggable = (kwargs.draggable as boolean) || false; if (!markers || !Array.isArray(markers)) { console.error('addMarkers requires markers array'); return; } const groupMarkers: Marker[] = []; for (let i = 0; i < markers.length; i++) { const markerData = markers[i]; const markerId = `${id}-${i}`; const scale = markerData.scale ?? defaultScale; const popupMaxWidth = markerData.popupMaxWidth || defaultPopupMaxWidth; const tooltipMaxWidth = markerData.tooltipMaxWidth || defaultTooltipMaxWidth; const marker = new Marker({ color, scale, draggable }).setLngLat(markerData.lngLat); if (markerData.popup) { marker.setPopup(new Popup({ maxWidth: popupMaxWidth }).setHTML(this.wrapWithContrastStyle(markerData.popup))); } // Add tooltip (shown on hover) if (markerData.tooltip) { const tooltipPopup = new Popup({ closeButton: false, closeOnClick: false, maxWidth: tooltipMaxWidth, offset: [0, -30 * scale], // Offset above the marker based on scale anchor: 'bottom', }); tooltipPopup.setHTML(this.wrapWithContrastStyle(markerData.tooltip)); const markerElement = marker.getElement(); const [lng, lat] = markerData.lngLat; let isHovering = false; markerElement.addEventListener('mouseenter', () => { isHovering = true; tooltipPopup.setLngLat([lng, lat]).addTo(this.map!); }); markerElement.addEventListener('mouseleave', (e: MouseEvent) => { // Check if we're moving to the popup itself const relatedTarget = e.relatedTarget as HTMLElement; if (relatedTarget?.closest('.maplibregl-popup')) { return; } isHovering = false; tooltipPopup.remove(); }); // Also handle leaving the popup tooltipPopup.on('close', () => { isHovering = false; }); } marker.addTo(this.map); this.markersMap.set(markerId, marker); groupMarkers.push(marker); } this.markerGroupsMap.set(id, groupMarkers); if (this.markerAdapter) { this.markerAdapter.addMarkerGroup(id, id, groupMarkers); } } private handleAddPopup(args: unknown[], kwargs: Record): void { if (!this.map) return; const layerId = kwargs.layerId as string; const properties = kwargs.properties as string[] | undefined; const template = kwargs.template as string | undefined; if (!layerId) { console.error('addPopup requires layerId'); return; } // Add click handler for the layer this.map.on('click', layerId, (e) => { if (!e.features || e.features.length === 0) return; const feature = e.features[0]; const props = feature.properties || {}; // CSS styles for better contrast and readability const tableStyle = 'border-collapse: collapse; font-size: 13px; color: #333;'; const cellStyle = 'padding: 4px 8px; border-bottom: 1px solid #ddd; color: #333;'; const keyStyle = 'font-weight: 600; color: #222;'; const valueStyle = 'color: #444;'; // Base style for custom templates const containerStyle = 'font-size: 13px; color: #333; line-height: 1.4;'; const templateStyles = ` `; let content: string; if (template) { // Replace placeholders in template and wrap with styled container const replaced = template.replace(/\{(\w+)\}/g, (match, key) => { return props[key] !== undefined ? String(props[key]) : match; }); content = `${templateStyles}
${replaced}
`; } else if (properties) { // Build table from specified properties const rows = properties .filter((key) => props[key] !== undefined) .map( (key) => `${key}${props[key]}` ) .join(''); content = `${rows}
`; } else { // Show all properties const rows = Object.entries(props) .map( ([key, value]) => `${key}${value}` ) .join(''); content = `${rows}
`; } new Popup() .setLngLat(e.lngLat) .setHTML(content) .addTo(this.map!); }); // Change cursor on hover this.map.on('mouseenter', layerId, () => { if (this.map) this.map.getCanvas().style.cursor = 'pointer'; }); this.map.on('mouseleave', layerId, () => { if (this.map) this.map.getCanvas().style.cursor = ''; }); } private handleAddLegend(args: unknown[], kwargs: Record): void { if (!this.map) return; const legendId = (kwargs.id as string) || `legend-${Date.now()}`; const title = (kwargs.title as string) || 'Legend'; const items = kwargs.items as Array<{ label: string; color: string }> || []; const position = (kwargs.position as string) || 'bottom-right'; const opacity = (kwargs.opacity as number) ?? 1.0; // Remove existing legend with the same ID if (this.legendsMap.has(legendId)) { this.handleRemoveLegend([legendId], {}); } // Create legend container const legendDiv = document.createElement('div'); legendDiv.id = legendId; legendDiv.className = 'maplibregl-ctrl legend-control'; legendDiv.style.cssText = ` background: rgba(255, 255, 255, ${opacity}); padding: 10px 14px; border-radius: 4px; box-shadow: 0 1px 4px rgba(0,0,0,0.3); font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; font-size: 12px; line-height: 1.4; max-width: 200px; `; // Add title const titleEl = document.createElement('div'); titleEl.style.cssText = 'font-weight: bold; margin-bottom: 8px; font-size: 13px; color: #333;'; titleEl.textContent = title; legendDiv.appendChild(titleEl); // Add items for (const item of items) { const row = document.createElement('div'); row.style.cssText = 'display: flex; align-items: center; margin-bottom: 4px;'; const colorBox = document.createElement('span'); colorBox.style.cssText = ` width: 16px; height: 16px; background-color: ${item.color}; margin-right: 8px; border-radius: 2px; flex-shrink: 0; `; row.appendChild(colorBox); const label = document.createElement('span'); label.style.color = '#333'; label.textContent = item.label; row.appendChild(label); legendDiv.appendChild(row); } // Get the appropriate control container const container = this.map.getContainer(); const positionClass = `maplibregl-ctrl-${position}`; let controlContainer = container.querySelector(`.${positionClass}`) as HTMLElement; if (!controlContainer) { // Create container if it doesn't exist const controlWrapper = container.querySelector('.maplibregl-control-container'); if (controlWrapper) { controlContainer = document.createElement('div'); controlContainer.className = `maplibregl-ctrl-${position.split('-')[0]} ${positionClass}`; controlWrapper.appendChild(controlContainer); } } if (controlContainer) { // Insert at beginning so legend appears above attribution controlContainer.insertBefore(legendDiv, controlContainer.firstChild); } this.legendsMap.set(legendId, legendDiv); } private handleRemoveLegend(args: unknown[], kwargs: Record): void { const legendId = args[0] as string | undefined; if (legendId) { // Remove specific legend const legendDiv = this.legendsMap.get(legendId); if (legendDiv && legendDiv.parentNode) { legendDiv.parentNode.removeChild(legendDiv); } this.legendsMap.delete(legendId); } else { // Remove all legends for (const [id, legendDiv] of this.legendsMap) { if (legendDiv.parentNode) { legendDiv.parentNode.removeChild(legendDiv); } } this.legendsMap.clear(); } } private handleAddTerrain(args: unknown[], kwargs: Record): void { if (!this.map) return; const source = kwargs.source as { url: string; encoding: string }; const exaggeration = (kwargs.exaggeration as number) ?? 1.0; if (!source || !source.url) { console.error('addTerrain requires source with url'); return; } const sourceId = 'terrain-dem'; // Add terrain source if (!this.map.getSource(sourceId)) { this.map.addSource(sourceId, { type: 'raster-dem', tiles: [source.url], tileSize: 256, encoding: source.encoding === 'mapbox' ? 'mapbox' : 'terrarium', }); } // Enable terrain this.map.setTerrain({ source: sourceId, exaggeration: exaggeration, }); } private handleMoveLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; const [layerId, beforeId] = args as [string, string | undefined]; if (!layerId) { console.error('moveLayer requires layerId'); return; } if (this.map.getLayer(layerId)) { this.map.moveLayer(layerId, beforeId || undefined); } } // ------------------------------------------------------------------------- // COG layer handlers (deck.gl) // ------------------------------------------------------------------------- /** * Convert a value to an accessor function for deck.gl layers. * Strings become property lookups, functions pass through, constants are returned as-is. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any protected makeAccessor(value: unknown, defaultProp: string, fallbackFn?: (d: any) => any): any { if (typeof value === 'string') { // eslint-disable-next-line @typescript-eslint/no-explicit-any return (d: any) => d[value]; } if (typeof value === 'function') { return value; } if (value !== undefined && value !== null) { return value; } // eslint-disable-next-line @typescript-eslint/no-explicit-any return fallbackFn || ((d: any) => d[defaultProp]); } /** * Initialize deck.gl overlay if not already created. */ protected initializeDeckOverlay(): void { if (this.deckOverlay || !this.map) return; this.deckOverlay = new MapboxOverlay({ interleaved: true, layers: [], }); this.map.addControl(this.deckOverlay as unknown as maplibregl.IControl); // Add an invisible sentinel layer as an ordering anchor. // Deck.gl layers use beforeId to render below this sentinel, // and native MapLibre layers added afterwards render above it. if (!this.map.getLayer(MapLibreRenderer.DECK_SENTINEL_ID)) { const sentinelSourceId = `${MapLibreRenderer.DECK_SENTINEL_ID}-source`; if (!this.map.getSource(sentinelSourceId)) { this.map.addSource(sentinelSourceId, { type: 'geojson', data: { type: 'FeatureCollection', features: [] }, }); } const insertBefore = this.userOverlayLayerIds.find( (id) => this.map && this.map.getLayer(id) ); this.map.addLayer({ id: MapLibreRenderer.DECK_SENTINEL_ID, type: 'fill', source: sentinelSourceId, paint: { 'fill-opacity': 0 }, }, insertBefore); } this.registerDeckAdaptersWithLayerControl(); } private registerDeckAdaptersWithLayerControl(): void { if (!this.map || !this.deckOverlay || !this.layerControlPlugin || this.deckAdaptersRegisteredWithLayerControl) { return; } const layerControl = this.layerControlPlugin.getControl(); if (!layerControl) { return; } if (!this.cogAdapter) { this.cogAdapter = new COGLayerAdapter(this.map, this.deckOverlay, this.deckLayers); } if (!this.deckLayerAdapter) { this.deckLayerAdapter = new DeckLayerAdapter(this.map, this.deckOverlay, this.deckLayers); } layerControl.registerCustomAdapter(this.cogAdapter); layerControl.registerCustomAdapter(this.deckLayerAdapter); this.deckAdaptersRegisteredWithLayerControl = true; this.scheduleLayerControlOrderSync(); } /** * Update deck.gl overlay with current layers. * Ensures all deck.gl layers have beforeId set to the sentinel layer * so they render below native MapLibre layers in interleaved mode. */ protected updateDeckOverlay(forceReanchor = false): void { if (!this.deckOverlay) return; const sentinelId = MapLibreRenderer.DECK_SENTINEL_ID; const hasSentinel = this.map?.getLayer(sentinelId); // Inject beforeId on deck.gl layers that don't have one if (hasSentinel) { for (const [id, layer] of this.deckLayers) { const typedLayer = layer as { clone?: (props: Record) => unknown; props?: { beforeId?: string } }; if (typedLayer.clone && (forceReanchor || !typedLayer.props?.beforeId)) { this.deckLayers.set(id, typedLayer.clone({ beforeId: sentinelId })); } } } const layers = Array.from(this.deckLayers.values()) as (false | null | undefined)[]; if (forceReanchor) { this.deckOverlay.setProps({ layers: [] }); } this.deckOverlay.setProps({ layers }); this.map?.triggerRepaint(); this.scheduleLayerControlOrderSync(); } private handleLayerControlReorder(layerOrder: string[]): void { if (!this.map || this.deckLayers.size === 0) { return; } this.reorderDeckLayersForLayerControl(layerOrder); const sentinelId = MapLibreRenderer.DECK_SENTINEL_ID; if (!this.map.getLayer(sentinelId)) { this.updateDeckOverlay(true); return; } const sentinelBeforeId = this.getSentinelBeforeIdForLayerControlOrder(layerOrder); try { this.map.moveLayer(sentinelId, sentinelBeforeId); } catch { // Ignore unsupported or transient move failures from custom layers. } this.updateDeckOverlay(true); } private reorderDeckLayersForLayerControl(layerOrder: string[]): void { if (this.deckLayers.size <= 1) { return; } const currentLayers = new globalThis.Map(this.deckLayers); const orderedDeckIds = layerOrder.filter(layerId => currentLayers.has(layerId)); const seen = new Set(); const reorderedEntries: Array<[string, unknown]> = []; for (const layerId of orderedDeckIds) { const layer = currentLayers.get(layerId); if (!layer || seen.has(layerId)) { continue; } reorderedEntries.push([layerId, layer]); seen.add(layerId); } for (const [layerId, layer] of currentLayers) { if (seen.has(layerId)) { continue; } reorderedEntries.push([layerId, layer]); } this.deckLayers.clear(); for (const [layerId, layer] of reorderedEntries) { this.deckLayers.set(layerId, layer); } } private getSentinelBeforeIdForLayerControlOrder(layerOrder: string[]): string | undefined { const lastDeckIndex = layerOrder.reduce((lastIndex, layerId, index) => { return this.deckLayers.has(layerId) ? index : lastIndex; }, -1); if (lastDeckIndex < 0) { return undefined; } for (let i = lastDeckIndex + 1; i < layerOrder.length; i++) { const layerId = layerOrder[i]; if (layerId !== MapLibreRenderer.DECK_SENTINEL_ID && this.map?.getLayer(layerId)) { return layerId; } } return undefined; } /** * Keep the layer control list aligned with deck.gl's real stack position. * The control library appends custom layers after native layers, but in * interleaved mode deck.gl layers actually render at the sentinel anchor. */ private getLayerControlOrder(): string[] { if (!this.map) { return []; } const styleLayers = this.map.getStyle()?.layers || []; const deckLayerIds = Array.from(this.deckLayers.keys()); if (styleLayers.length === 0) { return deckLayerIds; } const orderedLayerIds: string[] = []; let insertedDeckLayers = false; for (const layer of styleLayers) { if (layer.id === MapLibreRenderer.DECK_SENTINEL_ID) { if (!insertedDeckLayers) { orderedLayerIds.push(...deckLayerIds); insertedDeckLayers = true; } continue; } orderedLayerIds.push(layer.id); } if (!insertedDeckLayers) { orderedLayerIds.push(...deckLayerIds); } return orderedLayerIds; } private scheduleLayerControlOrderSync(): void { if (!this.layerControlPlugin) { return; } if (this.layerControlOrderSyncTimer !== null) { window.clearTimeout(this.layerControlOrderSyncTimer); } this.layerControlOrderSyncTimer = window.setTimeout(() => { this.layerControlPlugin?.syncLayerOrder(); this.layerControlOrderSyncTimer = null; }, 150); } protected handleAddCOGLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; // Initialize deck.gl overlay if needed this.initializeDeckOverlay(); const id = kwargs.id as string || `cog-${Date.now()}`; const geotiff = kwargs.geotiff as string; const fitBounds = kwargs.fitBounds !== false; const layer = new COGLayer({ id, geotiff, opacity: kwargs.opacity as number ?? 1, visible: kwargs.visible !== false, debug: kwargs.debug as boolean ?? false, debugOpacity: kwargs.debugOpacity as number ?? 0.25, maxError: kwargs.maxError as number ?? 0.125, geoKeysParser, onGeoTIFFLoad: (tiff: unknown, options: { geographicBounds: { west: number; south: number; east: number; north: number } }) => { if (fitBounds && this.map) { const { west, south, east, north } = options.geographicBounds; this.map.fitBounds( [[west, south], [east, north]], { padding: 40, duration: 1000 } ); } }, } as unknown as Record); this.deckLayers.set(id, layer); this.updateDeckOverlay(); // Notify adapter if it exists if (this.cogAdapter) { this.cogAdapter.notifyLayerAdded(id); } } private handleRemoveCOGLayer(args: unknown[], kwargs: Record): void { const [id] = args as [string]; // Notify adapter before removal if (this.cogAdapter) { this.cogAdapter.notifyLayerRemoved(id); } this.deckLayers.delete(id); this.updateDeckOverlay(); } // ------------------------------------------------------------------------- // Zarr layer handlers (@carbonplan/zarr-layer) // ------------------------------------------------------------------------- private handleAddZarrLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; const id = kwargs.id as string || `zarr-${Date.now()}`; const source = kwargs.source as string; const variable = kwargs.variable as string; const clim = kwargs.clim as [number, number] || [0, 100]; const colormap = kwargs.colormap as string[] || ['#000000', '#ffffff']; const selector = kwargs.selector || {}; const opacity = kwargs.opacity as number ?? 1; const layer = new ZarrLayer({ id, source, variable, clim, colormap, selector: selector as any, opacity, minzoom: kwargs.minzoom as number, maxzoom: kwargs.maxzoom as number, fillValue: kwargs.fillValue as number, spatialDimensions: kwargs.spatialDimensions as { lat?: string; lon?: string }, zarrVersion: kwargs.zarrVersion as 2 | 3 | undefined, bounds: kwargs.bounds as [number, number, number, number] | undefined, }); this.map.addLayer(layer as unknown as maplibregl.CustomLayerInterface); this.zarrLayers.set(id, layer); // Notify adapter if it exists if (this.zarrAdapter) { this.zarrAdapter.notifyLayerAdded(id); } } private handleRemoveZarrLayer(args: unknown[], kwargs: Record): void { const [id] = args as [string]; // Notify adapter before removal if (this.zarrAdapter) { this.zarrAdapter.notifyLayerRemoved(id); } if (this.map && this.map.getLayer(id)) { this.map.removeLayer(id); } this.zarrLayers.delete(id); } private handleUpdateZarrLayer(args: unknown[], kwargs: Record): void { const id = kwargs.id as string; const layer = this.zarrLayers.get(id); if (!layer) return; // Use the actual ZarrLayer methods if (kwargs.selector) layer.setSelector(kwargs.selector as Record); if (kwargs.clim) layer.setClim(kwargs.clim as [number, number]); if (kwargs.colormap) layer.setColormap(kwargs.colormap as string[]); if (kwargs.opacity !== undefined) layer.setOpacity(kwargs.opacity as number); } // ------------------------------------------------------------------------- // Arc layer handlers (deck.gl) // ------------------------------------------------------------------------- protected handleAddArcLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; // Initialize deck.gl overlay if needed this.initializeDeckOverlay(); const id = kwargs.id as string || `arc-${Date.now()}`; const data = kwargs.data as unknown[]; const layer = new ArcLayer({ id, data, pickable: kwargs.pickable !== false, opacity: kwargs.opacity as number ?? 0.8, getWidth: this.makeAccessor(kwargs.getWidth ?? kwargs.width, 'width', () => 1), getSourcePosition: this.makeAccessor(kwargs.getSourcePosition, 'source', (d: any) => d.source || d.from || d.sourcePosition), getTargetPosition: this.makeAccessor(kwargs.getTargetPosition, 'target', (d: any) => d.target || d.to || d.targetPosition), getSourceColor: this.makeAccessor(kwargs.getSourceColor ?? kwargs.sourceColor, 'sourceColor', () => [51, 136, 255, 255]), getTargetColor: this.makeAccessor(kwargs.getTargetColor ?? kwargs.targetColor, 'targetColor', () => [255, 136, 51, 255]), getHeight: this.makeAccessor(kwargs.getHeight ?? kwargs.height, 'height', () => 1), greatCircle: kwargs.greatCircle as boolean ?? false, }); this.deckLayers.set(id, layer); this.updateDeckOverlay(); // Notify adapter if it exists if (this.deckLayerAdapter) { this.deckLayerAdapter.notifyLayerAdded(id); } } private handleRemoveArcLayer(args: unknown[], kwargs: Record): void { const [id] = args as [string]; // Notify adapter before removal if (this.deckLayerAdapter) { this.deckLayerAdapter.notifyLayerRemoved(id); } this.deckLayers.delete(id); this.updateDeckOverlay(); } // ------------------------------------------------------------------------- // PointCloud layer handlers (deck.gl) // ------------------------------------------------------------------------- protected handleAddPointCloudLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; // Initialize deck.gl overlay if needed this.initializeDeckOverlay(); const id = kwargs.id as string || `pointcloud-${Date.now()}`; const data = kwargs.data as unknown[]; const layerProps: Record = { id, data, pickable: kwargs.pickable !== false, opacity: kwargs.opacity as number ?? 1, pointSize: kwargs.pointSize as number ?? 2, getPosition: this.makeAccessor(kwargs.getPosition, 'position', (d: any) => d.position || d.coordinates || [d.x, d.y, d.z]), getNormal: this.makeAccessor(kwargs.getNormal, 'normal', () => [0, 0, 1]), getColor: this.makeAccessor(kwargs.getColor ?? kwargs.color, 'color', () => [255, 255, 255, 255]), sizeUnits: kwargs.sizeUnits as 'pixels' | 'meters' | 'common' ?? 'pixels', }; // Only add coordinate system props if explicitly provided if (kwargs.coordinateSystem !== undefined && kwargs.coordinateSystem !== null) { layerProps.coordinateSystem = kwargs.coordinateSystem as number; } if (kwargs.coordinateOrigin !== undefined && kwargs.coordinateOrigin !== null) { layerProps.coordinateOrigin = kwargs.coordinateOrigin as [number, number, number]; } const layer = new PointCloudLayer(layerProps); this.deckLayers.set(id, layer); this.updateDeckOverlay(); // Notify adapter if it exists if (this.deckLayerAdapter) { this.deckLayerAdapter.notifyLayerAdded(id); } } private handleRemovePointCloudLayer(args: unknown[], kwargs: Record): void { const [id] = args as [string]; // Notify adapter before removal if (this.deckLayerAdapter) { this.deckLayerAdapter.notifyLayerRemoved(id); } this.deckLayers.delete(id); this.updateDeckOverlay(); } // ------------------------------------------------------------------------- // Additional deck.gl layer handlers // ------------------------------------------------------------------------- protected handleAddScatterplotLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; this.initializeDeckOverlay(); const id = kwargs.id as string || `scatterplot-${Date.now()}`; const data = kwargs.data as unknown[]; const layer = new ScatterplotLayer({ id, data, pickable: kwargs.pickable !== false, opacity: kwargs.opacity as number ?? 0.8, stroked: kwargs.stroked !== false, filled: kwargs.filled !== false, radiusScale: kwargs.radiusScale as number ?? 1, radiusMinPixels: kwargs.radiusMinPixels as number ?? 1, radiusMaxPixels: kwargs.radiusMaxPixels as number ?? 100, lineWidthMinPixels: kwargs.lineWidthMinPixels as number ?? 1, getPosition: this.makeAccessor( kwargs.getPosition, 'coordinates', (d: any) => d.coordinates || d.position || [d.lng || d.longitude, d.lat || d.latitude], ), getRadius: this.makeAccessor(kwargs.getRadius ?? kwargs.radius, 'radius', () => 5), getFillColor: this.makeAccessor(kwargs.getFillColor ?? kwargs.fillColor, 'fillColor', () => [51, 136, 255, 200]), getLineColor: this.makeAccessor(kwargs.getLineColor ?? kwargs.lineColor, 'lineColor', () => [255, 255, 255, 255]), } as any); this.deckLayers.set(id, layer); this.updateDeckOverlay(); if (this.deckLayerAdapter) { this.deckLayerAdapter.notifyLayerAdded(id); } } protected handleAddPathLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; this.initializeDeckOverlay(); const id = kwargs.id as string || `path-${Date.now()}`; const data = kwargs.data as unknown[]; const layer = new PathLayer({ id, data, pickable: kwargs.pickable !== false, opacity: kwargs.opacity as number ?? 0.8, widthScale: kwargs.widthScale as number ?? 1, widthMinPixels: kwargs.widthMinPixels as number ?? 1, getPath: this.makeAccessor(kwargs.getPath, 'path', (d: any) => d.path || d.coordinates), getColor: this.makeAccessor(kwargs.getColor ?? kwargs.color, 'color', () => [51, 136, 255, 200]), getWidth: this.makeAccessor(kwargs.getWidth ?? kwargs.width, 'width', () => 1), } as any); this.deckLayers.set(id, layer); this.updateDeckOverlay(); if (this.deckLayerAdapter) { this.deckLayerAdapter.notifyLayerAdded(id); } } protected handleAddPolygonLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; this.initializeDeckOverlay(); const id = kwargs.id as string || `polygon-${Date.now()}`; const data = kwargs.data as unknown[]; const layer = new PolygonLayer({ id, data, pickable: kwargs.pickable !== false, opacity: kwargs.opacity as number ?? 0.5, stroked: kwargs.stroked !== false, filled: kwargs.filled !== false, extruded: kwargs.extruded as boolean ?? false, wireframe: kwargs.wireframe as boolean ?? false, lineWidthMinPixels: kwargs.lineWidthMinPixels as number ?? 1, getPolygon: this.makeAccessor(kwargs.getPolygon, 'polygon', (d: any) => d.polygon || d.contour || d.coordinates), getElevation: this.makeAccessor(kwargs.getElevation ?? kwargs.elevation, 'elevation', () => 0), getFillColor: this.makeAccessor(kwargs.getFillColor ?? kwargs.fillColor, 'fillColor', () => [51, 136, 255, 128]), getLineColor: this.makeAccessor(kwargs.getLineColor ?? kwargs.lineColor, 'lineColor', () => [0, 0, 255, 255]), getLineWidth: this.makeAccessor(kwargs.getLineWidth ?? kwargs.lineWidth, 'lineWidth', () => 1), } as any); this.deckLayers.set(id, layer); this.updateDeckOverlay(); if (this.deckLayerAdapter) { this.deckLayerAdapter.notifyLayerAdded(id); } } protected handleAddHexagonLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; this.initializeDeckOverlay(); const id = kwargs.id as string || `hexagon-${Date.now()}`; const data = kwargs.data as unknown[]; const layer = new HexagonLayer({ id, data, pickable: kwargs.pickable !== false, opacity: kwargs.opacity as number ?? 0.8, extruded: kwargs.extruded as boolean ?? true, radius: kwargs.radius as number ?? 1000, elevationScale: kwargs.elevationScale as number ?? 4, getPosition: this.makeAccessor( kwargs.getPosition, 'coordinates', (d: any) => d.coordinates || d.position || [d.lng || d.longitude, d.lat || d.latitude], ), colorRange: kwargs.colorRange ?? [ [1, 152, 189], [73, 227, 206], [216, 254, 181], [254, 237, 177], [254, 173, 84], [209, 55, 78], ], } as any); this.deckLayers.set(id, layer); this.updateDeckOverlay(); if (this.deckLayerAdapter) { this.deckLayerAdapter.notifyLayerAdded(id); } } protected handleAddHeatmapLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; this.initializeDeckOverlay(); const id = kwargs.id as string || `heatmap-${Date.now()}`; const data = kwargs.data as unknown[]; const layer = new HeatmapLayer({ id, data, pickable: false, opacity: kwargs.opacity as number ?? 1, radiusPixels: kwargs.radiusPixels as number ?? 30, intensity: kwargs.intensity as number ?? 1, threshold: kwargs.threshold as number ?? 0.05, getPosition: this.makeAccessor( kwargs.getPosition, 'coordinates', (d: any) => d.coordinates || d.position || [d.lng || d.longitude, d.lat || d.latitude], ), getWeight: this.makeAccessor(kwargs.getWeight ?? kwargs.weight, 'weight', () => 1), colorRange: (kwargs.colorRange ?? [ [255, 255, 178, 25], [254, 217, 118, 85], [254, 178, 76, 127], [253, 141, 60, 170], [240, 59, 32, 212], [189, 0, 38, 255], ]) as any, } as any); this.deckLayers.set(id, layer); this.updateDeckOverlay(); if (this.deckLayerAdapter) { this.deckLayerAdapter.notifyLayerAdded(id); } } protected handleAddGridLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; this.initializeDeckOverlay(); const id = kwargs.id as string || `grid-${Date.now()}`; const data = kwargs.data as unknown[]; const layer = new GridLayer({ id, data, pickable: kwargs.pickable !== false, opacity: kwargs.opacity as number ?? 0.8, extruded: kwargs.extruded as boolean ?? true, cellSize: kwargs.cellSize as number ?? 200, elevationScale: kwargs.elevationScale as number ?? 4, getPosition: this.makeAccessor( kwargs.getPosition, 'coordinates', (d: any) => d.coordinates || d.position || [d.lng || d.longitude, d.lat || d.latitude], ), colorRange: kwargs.colorRange ?? [ [1, 152, 189], [73, 227, 206], [216, 254, 181], [254, 237, 177], [254, 173, 84], [209, 55, 78], ], } as any); this.deckLayers.set(id, layer); this.updateDeckOverlay(); if (this.deckLayerAdapter) { this.deckLayerAdapter.notifyLayerAdded(id); } } protected handleAddIconLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; this.initializeDeckOverlay(); const id = kwargs.id as string || `icon-${Date.now()}`; const data = kwargs.data as unknown[]; const layer = new IconLayer({ id, data, pickable: kwargs.pickable !== false, opacity: kwargs.opacity as number ?? 1, iconAtlas: kwargs.iconAtlas as string, iconMapping: kwargs.iconMapping, getPosition: this.makeAccessor( kwargs.getPosition, 'coordinates', (d: any) => d.coordinates || d.position || [d.lng || d.longitude, d.lat || d.latitude], ), getIcon: this.makeAccessor(kwargs.getIcon, 'icon', (d: any) => d.icon || 'marker'), getSize: this.makeAccessor(kwargs.getSize ?? kwargs.size, 'size', () => 20), getColor: this.makeAccessor(kwargs.getColor ?? kwargs.color, 'color', () => [255, 255, 255, 255]), } as any); this.deckLayers.set(id, layer); this.updateDeckOverlay(); if (this.deckLayerAdapter) { this.deckLayerAdapter.notifyLayerAdded(id); } } protected handleAddTextLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; this.initializeDeckOverlay(); const id = kwargs.id as string || `text-${Date.now()}`; const data = kwargs.data as unknown[]; const layer = new TextLayer({ id, data, pickable: kwargs.pickable !== false, opacity: kwargs.opacity as number ?? 1, getPosition: this.makeAccessor( kwargs.getPosition, 'coordinates', (d: any) => d.coordinates || d.position || [d.lng || d.longitude, d.lat || d.latitude], ), getText: this.makeAccessor(kwargs.getText, 'text', (d: any) => d.text || d.label || d.name || ''), getSize: this.makeAccessor(kwargs.getSize ?? kwargs.size, 'size', () => 12), getColor: this.makeAccessor(kwargs.getColor ?? kwargs.color, 'color', () => [0, 0, 0, 255]), getAngle: this.makeAccessor(kwargs.getAngle, 'angle', () => 0), getTextAnchor: (kwargs.getTextAnchor ?? 'middle') as any, getAlignmentBaseline: (kwargs.getAlignmentBaseline ?? 'center') as any, }); this.deckLayers.set(id, layer); this.updateDeckOverlay(); if (this.deckLayerAdapter) { this.deckLayerAdapter.notifyLayerAdded(id); } } protected handleAddGeoJsonLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; this.initializeDeckOverlay(); const id = kwargs.id as string || `geojson-${Date.now()}`; const data = kwargs.data as unknown; const layer = new GeoJsonLayer({ id, data, pickable: kwargs.pickable !== false, opacity: kwargs.opacity as number ?? 0.8, stroked: kwargs.stroked !== false, filled: kwargs.filled !== false, extruded: kwargs.extruded as boolean ?? false, wireframe: kwargs.wireframe as boolean ?? false, lineWidthMinPixels: kwargs.lineWidthMinPixels as number ?? 1, pointRadiusMinPixels: kwargs.pointRadiusMinPixels as number ?? 2, getFillColor: this.makeAccessor(kwargs.getFillColor ?? kwargs.fillColor, 'fillColor', () => [51, 136, 255, 128]), getLineColor: this.makeAccessor(kwargs.getLineColor ?? kwargs.lineColor, 'lineColor', () => [0, 0, 0, 255]), getLineWidth: this.makeAccessor(kwargs.getLineWidth ?? kwargs.lineWidth, 'lineWidth', () => 1), getPointRadius: this.makeAccessor(kwargs.getPointRadius ?? kwargs.pointRadius, 'pointRadius', () => 5), getElevation: this.makeAccessor(kwargs.getElevation ?? kwargs.elevation, 'elevation', () => 0), } as any); this.deckLayers.set(id, layer); this.updateDeckOverlay(); if (this.deckLayerAdapter) { this.deckLayerAdapter.notifyLayerAdded(id); } } protected handleAddContourLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; this.initializeDeckOverlay(); const id = kwargs.id as string || `contour-${Date.now()}`; const data = kwargs.data as unknown[]; const layer = new ContourLayer({ id, data, pickable: kwargs.pickable !== false, opacity: kwargs.opacity as number ?? 1, cellSize: kwargs.cellSize as number ?? 200, contours: kwargs.contours as any[] ?? [ { threshold: 1, color: [255, 255, 255], strokeWidth: 1 }, { threshold: 5, color: [51, 136, 255], strokeWidth: 2 }, { threshold: 10, color: [0, 0, 255], strokeWidth: 3 }, ], getPosition: this.makeAccessor( kwargs.getPosition, 'coordinates', (d: any) => d.coordinates || d.position || [d.lng || d.longitude, d.lat || d.latitude], ), getWeight: this.makeAccessor(kwargs.getWeight ?? kwargs.weight, 'weight', () => 1), } as any); this.deckLayers.set(id, layer); this.updateDeckOverlay(); if (this.deckLayerAdapter) { this.deckLayerAdapter.notifyLayerAdded(id); } } protected handleAddScreenGridLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; this.initializeDeckOverlay(); const id = kwargs.id as string || `screengrid-${Date.now()}`; const data = kwargs.data as unknown[]; const layer = new ScreenGridLayer({ id, data, pickable: kwargs.pickable !== false, opacity: kwargs.opacity as number ?? 0.8, cellSizePixels: kwargs.cellSizePixels as number ?? 50, getPosition: this.makeAccessor( kwargs.getPosition, 'coordinates', (d: any) => d.coordinates || d.position || [d.lng || d.longitude, d.lat || d.latitude], ), getWeight: this.makeAccessor(kwargs.getWeight ?? kwargs.weight, 'weight', () => 1), colorRange: (kwargs.colorRange ?? [ [255, 255, 178, 25], [254, 217, 118, 85], [254, 178, 76, 127], [253, 141, 60, 170], [240, 59, 32, 212], [189, 0, 38, 255], ]) as any, } as any); this.deckLayers.set(id, layer); this.updateDeckOverlay(); if (this.deckLayerAdapter) { this.deckLayerAdapter.notifyLayerAdded(id); } } protected handleAddTripsLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; this.initializeDeckOverlay(); const id = kwargs.id as string || `trips-${Date.now()}`; const data = kwargs.data as unknown[]; const layer = new TripsLayer({ id, data, pickable: kwargs.pickable !== false, opacity: kwargs.opacity as number ?? 0.8, widthMinPixels: kwargs.widthMinPixels as number ?? 2, trailLength: kwargs.trailLength as number ?? 180, currentTime: kwargs.currentTime as number ?? 0, getPath: this.makeAccessor(kwargs.getPath, 'waypoints', (d: any) => d.waypoints || d.path || d.coordinates), getTimestamps: this.makeAccessor(kwargs.getTimestamps, 'timestamps', (d: any) => d.timestamps), getColor: this.makeAccessor(kwargs.getColor ?? kwargs.color, 'color', () => [253, 128, 93]), } as any); this.deckLayers.set(id, layer); this.updateDeckOverlay(); if (this.deckLayerAdapter) { this.deckLayerAdapter.notifyLayerAdded(id); } } protected handleAddLineLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; this.initializeDeckOverlay(); const id = kwargs.id as string || `line-${Date.now()}`; const data = kwargs.data as unknown[]; const layer = new LineLayer({ id, data, pickable: kwargs.pickable !== false, opacity: kwargs.opacity as number ?? 0.8, widthMinPixels: kwargs.widthMinPixels as number ?? 1, getSourcePosition: this.makeAccessor(kwargs.getSourcePosition, 'sourcePosition', (d: any) => d.sourcePosition || d.source || d.from), getTargetPosition: this.makeAccessor(kwargs.getTargetPosition, 'targetPosition', (d: any) => d.targetPosition || d.target || d.to), getColor: this.makeAccessor(kwargs.getColor ?? kwargs.color, 'color', () => [51, 136, 255, 200]), getWidth: this.makeAccessor(kwargs.getWidth ?? kwargs.width, 'width', () => 1), } as any); this.deckLayers.set(id, layer); this.updateDeckOverlay(); if (this.deckLayerAdapter) { this.deckLayerAdapter.notifyLayerAdded(id); } } /** * Generic handler for adding any deck.gl layer type. * Routes to specific handlers based on layerType. */ protected handleAddDeckGLLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; const layerType = kwargs.layerType as string; if (!layerType) { console.warn('addDeckGLLayer called without layerType'); return; } // Map layer types to handler methods const handlerMap: Record) => void> = { 'ScatterplotLayer': this.handleAddScatterplotLayer.bind(this), 'ArcLayer': this.handleAddArcLayer.bind(this), 'PathLayer': this.handleAddPathLayer.bind(this), 'PolygonLayer': this.handleAddPolygonLayer.bind(this), 'HexagonLayer': this.handleAddHexagonLayer.bind(this), 'HeatmapLayer': this.handleAddHeatmapLayer.bind(this), 'GridLayer': this.handleAddGridLayer.bind(this), 'IconLayer': this.handleAddIconLayer.bind(this), 'TextLayer': this.handleAddTextLayer.bind(this), 'GeoJsonLayer': this.handleAddGeoJsonLayer.bind(this), 'ContourLayer': this.handleAddContourLayer.bind(this), 'ScreenGridLayer': this.handleAddScreenGridLayer.bind(this), 'PointCloudLayer': this.handleAddPointCloudLayer.bind(this), 'TripsLayer': this.handleAddTripsLayer.bind(this), 'LineLayer': this.handleAddLineLayer.bind(this), 'BitmapLayer': this.handleAddBitmapLayer.bind(this), 'ColumnLayer': this.handleAddColumnLayer.bind(this), 'GridCellLayer': this.handleAddGridCellLayer.bind(this), 'SolidPolygonLayer': this.handleAddSolidPolygonLayer.bind(this), // Heavy geo-layers and mesh-layers are only in DeckGLRenderer }; const handler = handlerMap[layerType]; if (handler) { handler(args, kwargs); } else { console.warn(`Unknown deck.gl layer type: ${layerType}`); } } /** * Remove a deck.gl layer by ID. */ protected handleRemoveDeckLayer(args: unknown[], kwargs: Record): void { const id = (args[0] as string) || (kwargs.id as string); if (!id) return; if (this.deckLayerAdapter) { this.deckLayerAdapter.notifyLayerRemoved(id); } this.deckLayers.delete(id); this.updateDeckOverlay(); } /** * Set visibility of a deck.gl layer. */ protected handleSetDeckLayerVisibility(args: unknown[], kwargs: Record): void { const id = (args[0] as string) || (kwargs.id as string); const visible = (args[1] as boolean) ?? (kwargs.visible as boolean) ?? true; if (!id) return; const layer = this.deckLayers.get(id) as { clone?: (props: Record) => unknown } | undefined; if (layer && typeof layer.clone === 'function') { const updatedLayer = layer.clone({ visible }); this.deckLayers.set(id, updatedLayer); this.updateDeckOverlay(); } } // ------------------------------------------------------------------------- // Accessor helper for deck.gl layer properties // ------------------------------------------------------------------------- // eslint-disable-next-line @typescript-eslint/no-explicit-any protected makeDeckAccessor(value: unknown, defaultProp: string, fallbackFn?: (d: any) => any): any { if (typeof value === 'string') { return (d: any) => d[value]; } if (typeof value === 'function') { return value; } if (value !== undefined && value !== null) { return value; } return fallbackFn || ((d: any) => d[defaultProp]); } // ------------------------------------------------------------------------- // Additional deck.gl layer handlers // ------------------------------------------------------------------------- protected handleAddBitmapLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; this.initializeDeckOverlay(); const id = kwargs.id as string || `bitmap-${Date.now()}`; const image = kwargs.image as string; const bounds = kwargs.bounds as [number, number, number, number]; const layer = new BitmapLayer({ id, image, bounds, opacity: kwargs.opacity as number ?? 1, visible: kwargs.visible !== false, pickable: kwargs.pickable as boolean ?? false, desaturate: kwargs.desaturate as number ?? 0, transparentColor: (kwargs.transparentColor ?? [0, 0, 0, 0]) as any, tintColor: (kwargs.tintColor ?? [255, 255, 255]) as any, }); this.deckLayers.set(id, layer); this.updateDeckOverlay(); if (this.deckLayerAdapter) { this.deckLayerAdapter.notifyLayerAdded(id); } } protected handleAddColumnLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; this.initializeDeckOverlay(); const id = kwargs.id as string || `column-${Date.now()}`; const data = kwargs.data as unknown[]; const layer = new ColumnLayer({ id, data, pickable: kwargs.pickable !== false, opacity: kwargs.opacity as number ?? 0.8, extruded: kwargs.extruded as boolean ?? true, diskResolution: kwargs.diskResolution as number ?? 20, radius: kwargs.radius as number ?? 1000, elevationScale: kwargs.elevationScale as number ?? 1, coverage: kwargs.coverage as number ?? 1, filled: kwargs.filled !== false, stroked: kwargs.stroked as boolean ?? false, wireframe: kwargs.wireframe as boolean ?? false, getPosition: this.makeDeckAccessor( kwargs.getPosition, 'coordinates', (d: any) => d.coordinates || d.position || [d.lng || d.longitude, d.lat || d.latitude], ), getFillColor: this.makeDeckAccessor(kwargs.getFillColor ?? kwargs.fillColor, 'fillColor', () => [255, 140, 0, 200]), getLineColor: this.makeDeckAccessor(kwargs.getLineColor ?? kwargs.lineColor, 'lineColor', () => [0, 0, 0, 255]), getElevation: this.makeDeckAccessor(kwargs.getElevation ?? kwargs.elevation, 'elevation', () => 1000), } as any); this.deckLayers.set(id, layer); this.updateDeckOverlay(); if (this.deckLayerAdapter) { this.deckLayerAdapter.notifyLayerAdded(id); } } protected handleAddGridCellLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; this.initializeDeckOverlay(); const id = kwargs.id as string || `gridcell-${Date.now()}`; const data = kwargs.data as unknown[]; const layer = new GridCellLayer({ id, data, pickable: kwargs.pickable !== false, opacity: kwargs.opacity as number ?? 0.8, extruded: kwargs.extruded as boolean ?? true, cellSize: kwargs.cellSize as number ?? 200, elevationScale: kwargs.elevationScale as number ?? 1, coverage: kwargs.coverage as number ?? 1, getPosition: this.makeDeckAccessor( kwargs.getPosition, 'coordinates', (d: any) => d.coordinates || d.position || [d.lng || d.longitude, d.lat || d.latitude], ), getColor: this.makeDeckAccessor(kwargs.getColor ?? kwargs.color, 'color', () => [255, 140, 0, 200]), getElevation: this.makeDeckAccessor(kwargs.getElevation ?? kwargs.elevation, 'elevation', () => 1000), } as any); this.deckLayers.set(id, layer); this.updateDeckOverlay(); if (this.deckLayerAdapter) { this.deckLayerAdapter.notifyLayerAdded(id); } } protected handleAddSolidPolygonLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; this.initializeDeckOverlay(); const id = kwargs.id as string || `solidpolygon-${Date.now()}`; const data = kwargs.data as unknown[]; const layer = new SolidPolygonLayer({ id, data, pickable: kwargs.pickable !== false, opacity: kwargs.opacity as number ?? 0.8, filled: kwargs.filled !== false, extruded: kwargs.extruded as boolean ?? false, wireframe: kwargs.wireframe as boolean ?? false, elevationScale: kwargs.elevationScale as number ?? 1, getPolygon: this.makeDeckAccessor(kwargs.getPolygon, 'polygon', (d: any) => d.polygon || d.contour || d.coordinates), getFillColor: this.makeDeckAccessor(kwargs.getFillColor ?? kwargs.fillColor, 'fillColor', () => [51, 136, 255, 128]), getLineColor: this.makeDeckAccessor(kwargs.getLineColor ?? kwargs.lineColor, 'lineColor', () => [0, 0, 0, 255]), getElevation: this.makeDeckAccessor(kwargs.getElevation ?? kwargs.elevation, 'elevation', () => 0), } as any); this.deckLayers.set(id, layer); this.updateDeckOverlay(); if (this.deckLayerAdapter) { this.deckLayerAdapter.notifyLayerAdded(id); } } // Heavy geo-layers (TileLayer, MVTLayer, Tile3DLayer, TerrainLayer, GreatCircleLayer, // H3HexagonLayer, H3ClusterLayer, S2Layer, QuadkeyLayer, GeohashLayer, WMSLayer) // and mesh-layers (SimpleMeshLayer, ScenegraphLayer) handlers are only in DeckGLRenderer // to keep the maplibre.js bundle lightweight and avoid heavy CommonJS dependencies. // Heavy geo-layers and mesh-layers handlers removed - see DeckGLRenderer // ------------------------------------------------------------------------- // Native MapLibre feature handlers (Section 3) // ------------------------------------------------------------------------- protected handleSetProjection(args: unknown[], kwargs: Record): void { if (!this.map) return; const projection = (kwargs.projection as string) || (args[0] as string) || 'mercator'; try { this.map.setProjection({ type: projection } as maplibregl.ProjectionSpecification); } catch (err) { console.error('setProjection error:', err); } } protected handleUpdateGeoJSONSource(args: unknown[], kwargs: Record): void { if (!this.map) return; const sourceId = kwargs.sourceId as string || args[0] as string; const data = kwargs.data; if (!sourceId) return; let source = this.map.getSource(sourceId) as maplibregl.GeoJSONSource; if (!source && !sourceId.endsWith('-source')) { source = this.map.getSource(sourceId + '-source') as maplibregl.GeoJSONSource; } if (source && typeof source.setData === 'function') { source.setData(data as any); } } protected handleAddMapImage(args: unknown[], kwargs: Record): void { if (!this.map) return; const name = kwargs.name as string || args[0] as string; const url = kwargs.url as string || args[1] as string; if (!name || !url) return; this.map.loadImage(url).then((response) => { if (response && response.data && !this.map!.hasImage(name)) { this.map!.addImage(name, response.data); } }).catch((err) => { console.warn(`Failed to load image '${name}':`, err); }); } private tooltipPopup: maplibregl.Popup | null = null; private tooltipLayerHandlers: Map void> = new Map(); protected handleAddTooltip(args: unknown[], kwargs: Record): void { if (!this.map) return; const layerId = kwargs.layerId as string; const template = kwargs.template as string || ''; const properties = kwargs.properties as string[] | undefined; if (!layerId) return; // Remove existing tooltip for this layer if (this.tooltipLayerHandlers.has(layerId)) { const oldHandler = this.tooltipLayerHandlers.get(layerId)!; this.map.off('mousemove', layerId, oldHandler); this.tooltipLayerHandlers.delete(layerId); } const popup = new Popup({ closeButton: false, closeOnClick: false, className: 'anymap-tooltip', }); const handler = (e: any) => { if (!e.features || e.features.length === 0) { popup.remove(); return; } const feature = e.features[0]; const props = feature.properties || {}; let html = template; if (template) { // Replace {property} placeholders and wrap in styled container const content = template.replace(/\{(\w+)\}/g, (_: string, key: string) => { return props[key] !== undefined ? String(props[key]) : ''; }); html = '
' + content + '
'; } else if (properties && properties.length > 0) { // Show only specified properties html = '
' + properties.map(p => `${p}: ${props[p] !== undefined ? props[p] : 'N/A'}`).join('
') + '
'; } else { // Show all properties html = '
' + Object.entries(props).map(([k, v]) => `${k}: ${v}`).join('
') + '
'; } popup.setLngLat(e.lngLat).setHTML(html).addTo(this.map!); }; this.map.on('mousemove', layerId, handler); this.map.on('mouseleave', layerId, () => { popup.remove(); }); this.tooltipLayerHandlers.set(layerId, handler); } protected handleRemoveTooltip(args: unknown[], kwargs: Record): void { if (!this.map) return; const layerId = kwargs.layerId as string; if (!layerId) return; if (this.tooltipLayerHandlers.has(layerId)) { const handler = this.tooltipLayerHandlers.get(layerId)!; this.map.off('mousemove', layerId, handler); this.tooltipLayerHandlers.delete(layerId); } } private coordinatesControl: HTMLDivElement | null = null; private coordinatesHandler: ((e: any) => void) | null = null; protected handleAddCoordinatesControl(args: unknown[], kwargs: Record): void { if (!this.map) return; const position = kwargs.position as string || 'bottom-left'; // Remove existing if (this.coordinatesControl) { this.coordinatesControl.remove(); if (this.coordinatesHandler) { this.map.off('mousemove', this.coordinatesHandler); } } const div = document.createElement('div'); div.className = 'maplibregl-ctrl maplibregl-ctrl-group anymap-coordinates'; div.style.cssText = 'padding:4px 8px;font-size:11px;font-family:monospace;background:rgba(255,255,255,0.9);pointer-events:none;'; div.textContent = 'Lng: 0.0000, Lat: 0.0000'; const precision = kwargs.precision as number ?? 4; const handler = (e: any) => { div.textContent = `Lng: ${e.lngLat.lng.toFixed(precision)}, Lat: ${e.lngLat.lat.toFixed(precision)}`; }; this.map.on('mousemove', handler); this.coordinatesHandler = handler; // Add to map container const controlContainer = this.map.getContainer().querySelector(`.maplibregl-ctrl-${position}`); if (controlContainer) { controlContainer.appendChild(div); } else { this.map.getContainer().appendChild(div); } this.coordinatesControl = div; } protected handleRemoveCoordinatesControl(args: unknown[], kwargs: Record): void { if (!this.map) return; if (this.coordinatesControl) { this.coordinatesControl.remove(); this.coordinatesControl = null; } if (this.coordinatesHandler) { this.map.off('mousemove', this.coordinatesHandler); this.coordinatesHandler = null; } } // ------------------------------------------------------------------------- // Time Slider handler (Section 4) // ------------------------------------------------------------------------- private timeSliderContainer: HTMLDivElement | null = null; protected handleAddTimeSlider(args: unknown[], kwargs: Record): void { if (!this.map) return; const layerId = kwargs.layerId as string; const property = kwargs.property as string; const min = kwargs.min as number ?? 0; const max = kwargs.max as number ?? 100; const step = kwargs.step as number ?? 1; const position = kwargs.position as string || 'bottom-left'; const label = kwargs.label as string || 'Time'; const autoPlay = kwargs.autoPlay as boolean ?? false; const interval = kwargs.interval as number ?? 500; // Remove existing slider this.handleRemoveTimeSlider(args, kwargs); const container = document.createElement('div'); container.className = 'maplibregl-ctrl maplibregl-ctrl-group anymap-time-slider'; container.style.cssText = 'padding:10px;background:rgba(255,255,255,0.95);min-width:250px;border-radius:4px;'; const labelEl = document.createElement('div'); labelEl.style.cssText = 'font-size:12px;font-weight:bold;margin-bottom:5px;'; labelEl.textContent = `${label}: ${min}`; const slider = document.createElement('input'); slider.type = 'range'; slider.min = String(min); slider.max = String(max); slider.step = String(step); slider.value = String(min); slider.style.cssText = 'width:100%;cursor:pointer;'; const playBtn = document.createElement('button'); playBtn.textContent = '\u25B6'; playBtn.style.cssText = 'margin-top:5px;padding:2px 8px;cursor:pointer;border:1px solid #ccc;border-radius:3px;background:#fff;'; let animTimer: number | null = null; const updateFilter = (value: number) => { labelEl.textContent = `${label}: ${value}`; if (this.map && layerId && property) { this.map.setFilter(layerId, ['<=', property, value]); } }; slider.addEventListener('input', () => { updateFilter(Number(slider.value)); }); const stopAnim = () => { if (animTimer !== null) { clearInterval(animTimer); animTimer = null; playBtn.textContent = '\u25B6'; } }; playBtn.addEventListener('click', () => { if (animTimer !== null) { stopAnim(); } else { playBtn.textContent = '\u23F8'; animTimer = window.setInterval(() => { let val = Number(slider.value) + step; if (val > max) val = min; slider.value = String(val); updateFilter(val); }, interval); } }); container.appendChild(labelEl); container.appendChild(slider); container.appendChild(playBtn); const controlContainer = this.map.getContainer().querySelector(`.maplibregl-ctrl-${position}`); if (controlContainer) { controlContainer.appendChild(container); } else { this.map.getContainer().appendChild(container); } this.timeSliderContainer = container; if (autoPlay) { playBtn.click(); } } protected handleRemoveTimeSlider(args: unknown[], kwargs: Record): void { if (this.timeSliderContainer) { this.timeSliderContainer.remove(); this.timeSliderContainer = null; } } // ------------------------------------------------------------------------- // UI Enhancement handlers (Section 6) // ------------------------------------------------------------------------- private swipeContainer: HTMLDivElement | null = null; private swipeHandler: (() => void) | null = null; protected handleAddSwipeMap(args: unknown[], kwargs: Record): void { if (!this.map) return; const leftLayer = kwargs.leftLayer as string; const rightLayer = kwargs.rightLayer as string; if (!leftLayer || !rightLayer) return; // Remove existing this.handleRemoveSwipeMap(args, kwargs); const container = this.map.getContainer(); const slider = document.createElement('div'); slider.className = 'anymap-swipe-slider'; slider.style.cssText = 'position:absolute;top:0;bottom:0;width:4px;background:#fff;cursor:ew-resize;z-index:10;left:50%;box-shadow:0 0 4px rgba(0,0,0,0.3);'; const handle = document.createElement('div'); handle.style.cssText = 'position:absolute;top:50%;left:-10px;width:24px;height:24px;background:#fff;border-radius:50%;border:2px solid #333;transform:translateY(-50%);cursor:ew-resize;'; slider.appendChild(handle); container.appendChild(slider); let isDragging = false; const updateClip = () => { const rect = container.getBoundingClientRect(); const sliderLeft = slider.offsetLeft; const clipRight = rect.width - sliderLeft; // Clip the right layer to show only on the right side of the slider this.map!.getContainer(); // Use clip-path on canvas layers const mapCanvas = this.map!.getCanvas(); if (mapCanvas) { // Set the left layer to show fully, clip the right layer if (this.map!.getLayer(leftLayer)) { // Left layer is fully visible } if (this.map!.getLayer(rightLayer)) { this.map!.setPaintProperty(rightLayer, 'raster-opacity', 1); } } }; const onMouseDown = (e: MouseEvent) => { isDragging = true; e.preventDefault(); }; const onMouseMove = (e: MouseEvent) => { if (!isDragging) return; const rect = container.getBoundingClientRect(); const x = Math.max(0, Math.min(e.clientX - rect.left, rect.width)); slider.style.left = `${x}px`; // Clip left layer if (this.map!.getLayer(leftLayer)) { (this.map! as any).setLayerClipBounds?.(leftLayer, [[0, 0], [x, rect.height]]); } if (this.map!.getLayer(rightLayer)) { (this.map! as any).setLayerClipBounds?.(rightLayer, [[x, 0], [rect.width, rect.height]]); } }; const onMouseUp = () => { isDragging = false; }; slider.addEventListener('mousedown', onMouseDown); document.addEventListener('mousemove', onMouseMove); document.addEventListener('mouseup', onMouseUp); this.swipeContainer = slider; this.swipeHandler = () => { slider.removeEventListener('mousedown', onMouseDown); document.removeEventListener('mousemove', onMouseMove); document.removeEventListener('mouseup', onMouseUp); }; } protected handleRemoveSwipeMap(args: unknown[], kwargs: Record): void { if (this.swipeContainer) { this.swipeContainer.remove(); this.swipeContainer = null; } if (this.swipeHandler) { this.swipeHandler(); this.swipeHandler = null; } } private opacitySliderContainer: Map = new Map(); protected handleAddOpacitySlider(args: unknown[], kwargs: Record): void { if (!this.map) return; const layerId = kwargs.layerId as string; const position = kwargs.position as string || 'top-right'; const label = kwargs.label as string || layerId; if (!layerId) return; // Remove existing for this layer this.removeOpacitySliderForLayer(layerId); const container = document.createElement('div'); container.className = 'maplibregl-ctrl maplibregl-ctrl-group anymap-opacity-slider'; container.style.cssText = 'padding:8px;background:rgba(255,255,255,0.95);min-width:150px;border-radius:4px;'; const labelEl = document.createElement('div'); labelEl.style.cssText = 'font-size:11px;margin-bottom:4px;'; labelEl.textContent = `${label}: 100%`; const slider = document.createElement('input'); slider.type = 'range'; slider.min = '0'; slider.max = '100'; slider.value = '100'; slider.style.cssText = 'width:100%;cursor:pointer;'; slider.addEventListener('input', () => { const opacity = Number(slider.value) / 100; labelEl.textContent = `${label}: ${slider.value}%`; // Try to set opacity on different layer types if (this.map!.getLayer(layerId)) { try { const layerObj = this.map!.getLayer(layerId); const layerType = (layerObj as any)?.type; if (layerType === 'raster') { this.map!.setPaintProperty(layerId, 'raster-opacity', opacity); } else if (layerType === 'fill') { this.map!.setPaintProperty(layerId, 'fill-opacity', opacity); } else if (layerType === 'line') { this.map!.setPaintProperty(layerId, 'line-opacity', opacity); } else if (layerType === 'circle') { this.map!.setPaintProperty(layerId, 'circle-opacity', opacity); } else if (layerType === 'symbol') { this.map!.setPaintProperty(layerId, 'icon-opacity', opacity); this.map!.setPaintProperty(layerId, 'text-opacity', opacity); } else if (layerType === 'fill-extrusion') { this.map!.setPaintProperty(layerId, 'fill-extrusion-opacity', opacity); } } catch { // Deck.gl layer - try deck.gl approach const deckLayer = this.deckLayers.get(layerId) as { clone?: (props: Record) => unknown } | undefined; if (deckLayer && typeof deckLayer.clone === 'function') { const updated = deckLayer.clone({ opacity }); this.deckLayers.set(layerId, updated); this.updateDeckOverlay(); } } } }); container.appendChild(labelEl); container.appendChild(slider); const controlContainer = this.map.getContainer().querySelector(`.maplibregl-ctrl-${position}`); if (controlContainer) { controlContainer.appendChild(container); } this.opacitySliderContainer.set(layerId, container); } private removeOpacitySliderForLayer(layerId: string): void { const existing = this.opacitySliderContainer.get(layerId); if (existing) { existing.remove(); this.opacitySliderContainer.delete(layerId); } } protected handleRemoveOpacitySlider(args: unknown[], kwargs: Record): void { const layerId = kwargs.layerId as string; if (layerId) { this.removeOpacitySliderForLayer(layerId); } } private styleSwitcherContainer: HTMLDivElement | null = null; protected handleAddStyleSwitcher(args: unknown[], kwargs: Record): void { if (!this.map) return; const styles = kwargs.styles as Record; const position = kwargs.position as string || 'top-right'; if (!styles || Object.keys(styles).length === 0) return; // Remove existing this.handleRemoveStyleSwitcher(args, kwargs); const container = document.createElement('div'); container.className = 'maplibregl-ctrl maplibregl-ctrl-group anymap-style-switcher'; container.style.cssText = 'padding:8px;background:rgba(255,255,255,0.95);border-radius:4px;'; const select = document.createElement('select'); select.style.cssText = 'font-size:12px;padding:2px 4px;border:1px solid #ccc;border-radius:3px;cursor:pointer;'; for (const [name, url] of Object.entries(styles)) { const option = document.createElement('option'); option.value = url; option.textContent = name; select.appendChild(option); } select.addEventListener('change', () => { this.map!.setStyle(select.value); }); container.appendChild(select); const controlContainer = this.map.getContainer().querySelector(`.maplibregl-ctrl-${position}`); if (controlContainer) { controlContainer.appendChild(container); } this.styleSwitcherContainer = container; } protected handleRemoveStyleSwitcher(args: unknown[], kwargs: Record): void { if (this.styleSwitcherContainer) { this.styleSwitcherContainer.remove(); this.styleSwitcherContainer = null; } } // ------------------------------------------------------------------------- // Data Export handlers (Section 7) // ------------------------------------------------------------------------- protected handleGetVisibleFeatures(args: unknown[], kwargs: Record): void { if (!this.map) return; const layers = kwargs.layers as string[] | undefined; try { const features = layers ? this.map.queryRenderedFeatures(undefined, { layers }) : this.map.queryRenderedFeatures(); const geojson: FeatureCollection = { type: 'FeatureCollection', features: features.map(f => ({ type: 'Feature' as const, geometry: f.geometry, properties: f.properties, })), }; // Send back via model if (this.model) { this.model.set('_queried_features', { type: 'visible_features', data: geojson, }); this.model.save_changes(); } } catch (err) { console.warn('Error getting visible features:', err); } } protected handleGetLayerData(args: unknown[], kwargs: Record): void { if (!this.map) return; const sourceId = kwargs.sourceId as string; if (!sourceId) return; let features: maplibregl.GeoJSONFeature[] = []; let resolvedSourceId = sourceId; // Try the given sourceId first try { features = this.map.querySourceFeatures(sourceId); } catch { // Source doesn't exist with this ID } // If no results, try with '-source' suffix // (add_geojson creates sources as '{name}-source') if (features.length === 0 && !sourceId.endsWith('-source')) { const altSourceId = sourceId + '-source'; try { const altFeatures = this.map.querySourceFeatures(altSourceId); if (altFeatures.length > 0) { features = altFeatures; resolvedSourceId = altSourceId; } } catch { // alt source doesn't exist either } } const geojson: FeatureCollection = { type: 'FeatureCollection', features: features.map(f => ({ type: 'Feature' as const, geometry: f.geometry, properties: f.properties, })), }; if (this.model) { this.model.set('_queried_features', { type: 'layer_data', sourceId: resolvedSourceId, data: geojson, }); this.model.save_changes(); } } // ------------------------------------------------------------------------- // LiDAR layer handlers (maplibre-gl-lidar) // ------------------------------------------------------------------------- /** * Add the LiDAR control panel. */ private handleAddLidarControl(args: unknown[], kwargs: Record): void { if (!this.map) return; // Don't add if already exists if (this.lidarControl) { console.warn('LiDAR control already exists'); return; } const options = { position: (kwargs.position as string) || 'top-right', collapsed: kwargs.collapsed !== false, title: (kwargs.title as string) || 'LiDAR Viewer', panelWidth: (kwargs.panelWidth as number) || 365, panelMaxHeight: (kwargs.panelMaxHeight as number) || 600, pointSize: (kwargs.pointSize as number) || 2, opacity: (kwargs.opacity as number) || 1.0, colorScheme: (kwargs.colorScheme as string) || 'elevation', usePercentile: kwargs.usePercentile !== false, pointBudget: (kwargs.pointBudget as number) || 1000000, pickable: kwargs.pickable === true, autoZoom: kwargs.autoZoom !== false, copcLoadingMode: kwargs.copcLoadingMode as 'full' | 'dynamic' | undefined, streamingPointBudget: (kwargs.streamingPointBudget as number) || 5000000, }; // Create and add the LiDAR control this.lidarControl = new LidarControl(options as LidarControlOptions); this.map.addControl( this.lidarControl as unknown as maplibregl.IControl, options.position as ControlPosition ); // Listen for load events to track loaded point clouds this.lidarControl.on('load', (event) => { const info = event.pointCloud as { id: string; name: string; pointCount: number; source?: string } | undefined; if (info && 'name' in info) { this.lidarLayers.set(info.id, info.source || ''); this.sendEvent('lidar:load', { id: info.id, name: info.name, pointCount: info.pointCount }); } }); this.lidarControl.on('unload', (event) => { const pointCloud = event.pointCloud as { id: string } | undefined; if (pointCloud) { this.lidarLayers.delete(pointCloud.id); this.sendEvent('lidar:unload', { id: pointCloud.id }); } }); // Register with existing layer control if present this.registerLidarAdapterWithLayerControl(); } /** * Register the LiDAR adapter with the layer control if it exists. * This enables dynamic registration when LiDAR layers are added after the layer control. */ private registerLidarAdapterWithLayerControl(): void { if (!this.lidarControl || !this.layerControlPlugin) return; const layerControl = this.layerControlPlugin.getControl(); if (!layerControl) return; // Create adapter if not exists if (!this.lidarAdapter) { this.lidarAdapter = new LidarLayerAdapter(this.lidarControl); } // Register the adapter with the layer control layerControl.registerCustomAdapter(this.lidarAdapter); } /** * Add a LiDAR layer programmatically (loads from URL or base64 data). */ private handleAddLidarLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; const source = kwargs.source as string; const name = (kwargs.name as string) || `lidar-${Date.now()}`; const isBase64 = kwargs.isBase64 === true; if (!source) { console.error('LiDAR layer requires a source URL or base64 data'); return; } // Create LiDAR control if not exists (invisible panel mode) if (!this.lidarControl) { this.lidarControl = new LidarControl({ collapsed: true, position: 'top-right', pointSize: (kwargs.pointSize as number) || 2, opacity: (kwargs.opacity as number) || 1.0, colorScheme: (kwargs.colorScheme as string) || 'elevation', usePercentile: kwargs.usePercentile !== false, pointBudget: (kwargs.pointBudget as number) || 1000000, pickable: kwargs.pickable !== false, autoZoom: kwargs.autoZoom !== false, } as LidarControlOptions); this.map.addControl(this.lidarControl as unknown as maplibregl.IControl, 'top-right'); // Set up event listeners this.lidarControl.on('load', (event) => { const info = event.pointCloud as { id: string; name: string; pointCount: number; source?: string } | undefined; if (info && 'name' in info) { this.lidarLayers.set(info.id, info.source || ''); this.sendEvent('lidar:load', { id: info.id, name: info.name, pointCount: info.pointCount }); } }); this.lidarControl.on('unload', (event) => { const pointCloud = event.pointCloud as { id: string } | undefined; if (pointCloud) { this.lidarLayers.delete(pointCloud.id); this.sendEvent('lidar:unload', { id: pointCloud.id }); } }); // Register with existing layer control if present this.registerLidarAdapterWithLayerControl(); } // Apply styling options if (kwargs.colorScheme) { this.lidarControl.setColorScheme(kwargs.colorScheme as LidarColorScheme); } if (kwargs.pointSize !== undefined) { this.lidarControl.setPointSize(kwargs.pointSize as number); } if (kwargs.opacity !== undefined) { this.lidarControl.setOpacity(kwargs.opacity as number); } if (kwargs.pickable !== undefined) { this.lidarControl.setPickable(kwargs.pickable as boolean); } // Load the point cloud const loadOptions = { id: name, name: (kwargs.filename as string) || name, }; if (isBase64) { // Convert base64 to ArrayBuffer const binaryString = atob(source); const bytes = new Uint8Array(binaryString.length); for (let i = 0; i < binaryString.length; i++) { bytes[i] = binaryString.charCodeAt(i); } const arrayBuffer = bytes.buffer; // Load from ArrayBuffer const streamingMode = kwargs.streamingMode !== false; if (streamingMode) { this.lidarControl.loadPointCloudStreaming(arrayBuffer, loadOptions as any); } else { this.lidarControl.loadPointCloud(arrayBuffer, loadOptions as any); } } else { // Load from URL const streamingMode = kwargs.streamingMode !== false; if (streamingMode) { this.lidarControl.loadPointCloudStreaming(source, loadOptions as any); } else { this.lidarControl.loadPointCloud(source, loadOptions as any); } } // Track the layer this.lidarLayers.set(name, source); } /** * Remove a LiDAR layer. */ private handleRemoveLidarLayer(args: unknown[], kwargs: Record): void { if (!this.lidarControl) return; const id = kwargs.id as string; if (id) { this.lidarControl.unloadPointCloud(id); this.lidarLayers.delete(id); } else { // Remove all layers this.lidarControl.unloadPointCloud(); this.lidarLayers.clear(); } } /** * Set LiDAR color scheme. */ private handleSetLidarColorScheme(args: unknown[], kwargs: Record): void { if (!this.lidarControl) return; const colorScheme = kwargs.colorScheme as string; if (colorScheme) { this.lidarControl.setColorScheme(colorScheme as any); } } /** * Set LiDAR point size. */ private handleSetLidarPointSize(args: unknown[], kwargs: Record): void { if (!this.lidarControl) return; const pointSize = kwargs.pointSize as number; if (pointSize !== undefined) { this.lidarControl.setPointSize(pointSize); } } /** * Set LiDAR layer opacity. */ private handleSetLidarOpacity(args: unknown[], kwargs: Record): void { if (!this.lidarControl) return; const opacity = kwargs.opacity as number; if (opacity !== undefined) { this.lidarControl.setOpacity(opacity); } } // ------------------------------------------------------------------------- // maplibre-gl-components control handlers // ------------------------------------------------------------------------- private handleAddPMTilesControl(args: unknown[], kwargs: Record): void { if (!this.map) return; const position = (kwargs.position as ControlPosition) || 'top-right'; const collapsed = kwargs.collapsed !== false; const defaultUrl = kwargs.defaultUrl as string || ''; const loadDefaultUrl = kwargs.loadDefaultUrl as boolean || false; // Remove existing control if present const existingControl = this.controlsMap.get('pmtiles-control'); if (existingControl) { this.map.removeControl(existingControl); this.controlsMap.delete('pmtiles-control'); } // Create PMTiles control this.pmtilesLayerControl = new PMTilesLayerControl({ collapsed, defaultUrl, loadDefaultUrl, defaultOpacity: (kwargs.defaultOpacity as number) ?? 1, defaultFillColor: kwargs.defaultFillColor as string || 'steelblue', defaultLineColor: kwargs.defaultLineColor as string || '#333', defaultPickable: kwargs.defaultPickable !== false, }); this.map.addControl(this.pmtilesLayerControl as unknown as maplibregl.IControl, position); this.controlsMap.set('pmtiles-control', this.pmtilesLayerControl as unknown as maplibregl.IControl); // Set up event listeners this.pmtilesLayerControl.on('layeradd', (event) => { console.debug('PMTiles layer added:', event.url); this.sendEvent('pmtiles_layer_add', { url: event.url, layerId: event.layerId }); }); this.pmtilesLayerControl.on('layerremove', (event) => { console.debug('PMTiles layer removed:', event.layerId); this.sendEvent('pmtiles_layer_remove', { layerId: event.layerId }); }); this.pmtilesLayerControl.on('error', (event) => { console.error('PMTiles error:', event.error); this.sendEvent('pmtiles_error', { error: event.error }); }); } private handleAddCogControl(args: unknown[], kwargs: Record): void { if (!this.map) return; const position = (kwargs.position as ControlPosition) || 'top-right'; const collapsed = kwargs.collapsed !== false; const defaultUrl = kwargs.defaultUrl as string || ''; const loadDefaultUrl = kwargs.loadDefaultUrl as boolean || false; // Remove existing control if present const existingControl = this.controlsMap.get('cog-control'); if (existingControl) { this.map.removeControl(existingControl); this.controlsMap.delete('cog-control'); } // Create COG control this.cogLayerUiControl = new CogLayerControl({ collapsed, defaultUrl, loadDefaultUrl, defaultOpacity: (kwargs.defaultOpacity as number) ?? 1, defaultColormap: (kwargs.defaultColormap as string || 'viridis') as any, defaultBands: kwargs.defaultBands as string || '1', defaultRescaleMin: (kwargs.defaultRescaleMin as number) ?? 0, defaultRescaleMax: (kwargs.defaultRescaleMax as number) ?? 255, }); this.map.addControl(this.cogLayerUiControl as unknown as maplibregl.IControl, position); this.controlsMap.set('cog-control', this.cogLayerUiControl as unknown as maplibregl.IControl); // Set up event listeners this.cogLayerUiControl.on('layeradd', (event) => { console.debug('COG layer added:', event.url); this.sendEvent('cog_layer_add', { url: event.url, layerId: event.layerId }); }); this.cogLayerUiControl.on('layerremove', (event) => { console.debug('COG layer removed:', event.layerId); this.sendEvent('cog_layer_remove', { layerId: event.layerId }); }); this.cogLayerUiControl.on('error', (event) => { console.error('COG error:', event.error); this.sendEvent('cog_error', { error: event.error }); }); } private handleAddZarrControl(args: unknown[], kwargs: Record): void { if (!this.map) return; const position = (kwargs.position as ControlPosition) || 'top-right'; const collapsed = kwargs.collapsed !== false; const defaultUrl = kwargs.defaultUrl as string || ''; const loadDefaultUrl = kwargs.loadDefaultUrl as boolean || false; // Remove existing control if present const existingControl = this.controlsMap.get('zarr-control'); if (existingControl) { this.map.removeControl(existingControl); this.controlsMap.delete('zarr-control'); } // Create Zarr control this.zarrLayerUiControl = new ZarrLayerControl({ collapsed, defaultUrl, loadDefaultUrl, defaultOpacity: (kwargs.defaultOpacity as number) ?? 1, defaultVariable: kwargs.defaultVariable as string || '', defaultClim: kwargs.defaultClim as [number, number] || [0, 1], }); this.map.addControl(this.zarrLayerUiControl as unknown as maplibregl.IControl, position); this.controlsMap.set('zarr-control', this.zarrLayerUiControl as unknown as maplibregl.IControl); // Set up event listeners this.zarrLayerUiControl.on('layeradd', (event) => { console.debug('Zarr layer added:', event.url); this.sendEvent('zarr_layer_add', { url: event.url, layerId: event.layerId }); }); this.zarrLayerUiControl.on('layerremove', (event) => { console.debug('Zarr layer removed:', event.layerId); this.sendEvent('zarr_layer_remove', { layerId: event.layerId }); }); this.zarrLayerUiControl.on('error', (event) => { console.error('Zarr error:', event.error); this.sendEvent('zarr_error', { error: event.error }); }); } private handleAddVectorControl(args: unknown[], kwargs: Record): void { if (!this.map) return; const position = (kwargs.position as ControlPosition) || 'top-right'; const collapsed = kwargs.collapsed !== false; const defaultUrl = kwargs.defaultUrl as string || ''; const loadDefaultUrl = kwargs.loadDefaultUrl as boolean || false; // Remove existing control if present const existingControl = this.controlsMap.get('vector-control'); if (existingControl) { this.map.removeControl(existingControl); this.controlsMap.delete('vector-control'); } // Create AddVector control this.addVectorControl = new AddVectorControl({ collapsed, defaultUrl, loadDefaultUrl, defaultOpacity: (kwargs.defaultOpacity as number) ?? 1, defaultFillColor: kwargs.defaultFillColor as string || '#3388ff', defaultStrokeColor: kwargs.defaultStrokeColor as string || '#3388ff', fitBounds: kwargs.fitBounds !== false, }); this.map.addControl(this.addVectorControl as unknown as maplibregl.IControl, position); this.controlsMap.set('vector-control', this.addVectorControl as unknown as maplibregl.IControl); // Set up event listeners this.addVectorControl.on('layeradd', (event) => { console.debug('Vector layer added:', event.url); this.sendEvent('vector_layer_add', { url: event.url, layerId: event.layerId }); }); this.addVectorControl.on('layerremove', (event) => { console.debug('Vector layer removed:', event.layerId); this.sendEvent('vector_layer_remove', { layerId: event.layerId }); }); this.addVectorControl.on('error', (event) => { console.error('Vector error:', event.error); this.sendEvent('vector_error', { error: event.error }); }); } private handleAddControlGrid(_args: unknown[], kwargs: Record): void { if (!this.map) return; const position = (kwargs.position as string) || 'top-right'; // Remove existing control grid if present if (this.controlGrid) { this.map.removeControl(this.controlGrid as unknown as maplibregl.IControl); this.controlsMap.delete('control-grid'); this.controlGrid = null; } // Build options for addControlGrid const options: Record = { position }; if (kwargs.defaultControls !== undefined && kwargs.defaultControls !== null) { options.defaultControls = kwargs.defaultControls; } if (kwargs.exclude !== undefined && kwargs.exclude !== null) { options.exclude = kwargs.exclude; } if (kwargs.rows !== undefined && kwargs.rows !== null) { options.rows = kwargs.rows; } if (kwargs.columns !== undefined && kwargs.columns !== null) { options.columns = kwargs.columns; } if (kwargs.collapsed !== undefined) { options.collapsed = kwargs.collapsed; } if (kwargs.collapsible !== undefined) { options.collapsible = kwargs.collapsible; } if (kwargs.title !== undefined) { options.title = kwargs.title; } if (kwargs.showRowColumnControls !== undefined) { options.showRowColumnControls = kwargs.showRowColumnControls; } if (kwargs.gap !== undefined && kwargs.gap !== null) { options.gap = kwargs.gap; } if (kwargs.basemapStyleUrl !== undefined) { options.basemapStyleUrl = kwargs.basemapStyleUrl; } else { // Use the current map style URL as default for SwipeControl const style = this.model.get('style'); if (typeof style === 'string') { options.basemapStyleUrl = style; } } if (kwargs.excludeLayers !== undefined && kwargs.excludeLayers !== null) { options.excludeLayers = kwargs.excludeLayers; } if (kwargs.bookmarkOptions !== undefined && kwargs.bookmarkOptions !== null) { options.bookmarkOptions = kwargs.bookmarkOptions; } this.controlGrid = addControlGrid(this.map, options as Parameters[1]); this.controlsMap.set('control-grid', this.controlGrid as unknown as maplibregl.IControl); // Register adapters with LayerControl if present const layerControl = this.layerControlPlugin?.getControl(); if (layerControl) { for (const adapter of this.controlGrid.getAdapters()) { layerControl.registerCustomAdapter(adapter); } } this.stateManager.addControl('control-grid', 'control-grid', position, kwargs); } // ------------------------------------------------------------------------- // Trait change handlers // ------------------------------------------------------------------------- protected onCenterChange(): void { if (this.map && this.isMapReady) { const center = this.model.get('center'); this.map.setCenter(center as [number, number]); } } protected onZoomChange(): void { if (this.map && this.isMapReady) { const zoom = this.model.get('zoom'); this.map.setZoom(zoom); } } protected onStyleChange(): void { if (this.map && this.isMapReady) { const style = this.model.get('style'); this.map.setStyle(typeof style === 'string' ? style : (style as maplibregl.StyleSpecification)); } } // ------------------------------------------------------------------------- // PMTiles layer handlers // ------------------------------------------------------------------------- /** * Generate visually distinct colors using evenly spaced HSL hues. */ private generateDistinctColors(count: number): string[] { const colors: string[] = []; for (let i = 0; i < count; i++) { const hue = (i * 360 / count) % 360; const saturation = 65 + (i % 3) * 10; const lightness = 45 + (i % 2) * 10; colors.push(`hsl(${hue}, ${saturation}%, ${lightness}%)`); } return colors; } /** * Map geometry type string to MapLibre layer type. */ private geometryToLayerType(geometryType: string): 'fill' | 'line' | 'circle' | 'symbol' { const lower = geometryType.toLowerCase(); if (lower.includes('polygon')) return 'fill'; if (lower.includes('line')) return 'line'; if (lower.includes('point')) return 'circle'; return 'fill'; } /** * Infer MapLibre layer type from a source layer name when geometry_type * is not available in the PMTiles metadata. */ private inferLayerTypeFromName(layerName: string): 'fill' | 'line' | 'circle' | 'symbol' { const lower = layerName.toLowerCase(); // Names that typically represent line geometries const linePatterns = [ 'road', 'street', 'highway', 'path', 'route', 'rail', 'transit', 'boundary', 'boundaries', 'border', 'river', 'stream', 'canal', 'waterway', 'line', 'edge', 'track', 'ferry', 'bridge', 'tunnel', 'physical_line', 'transportation', ]; // Names that typically represent point geometries const pointPatterns = [ 'poi', 'pois', 'point', 'place', 'places', 'marker', 'stop', 'station', 'node', 'peak', 'city', 'town', 'village', 'label', 'symbol', 'icon', 'address', 'physical_point', 'mountain_peak', ]; for (const pattern of linePatterns) { if (lower === pattern || lower.includes(pattern)) return 'line'; } for (const pattern of pointPatterns) { if (lower === pattern || lower.includes(pattern)) return 'circle'; } return 'fill'; } private async handleAddPMTilesLayer(args: unknown[], kwargs: Record): Promise { if (!this.map) return; const url = kwargs.url as string; const layerId = kwargs.id as string; const sourceType = (kwargs.sourceType as string) || 'vector'; const opacity = (kwargs.opacity as number) ?? 1.0; const visible = kwargs.visible !== false; const style = (kwargs.style as Record) || {}; const fitBounds = kwargs.fitBounds === true; // Ensure pmtiles:// protocol prefix for the map source const pmtilesUrl = url.startsWith('pmtiles://') ? url : `pmtiles://${url}`; // Strip pmtiles:// prefix for the PMTiles constructor (needs raw HTTP URL) const archiveUrl = url.startsWith('pmtiles://') ? url.slice('pmtiles://'.length) : url; try { // Add source const sourceId = `${layerId}-source`; if (!this.map.getSource(sourceId)) { const sourceConfig = { type: sourceType as 'vector' | 'raster', url: pmtilesUrl, }; this.map.addSource(sourceId, sourceConfig); // Persist source state for multi-cell rendering this.stateManager.addSource(sourceId, sourceConfig as unknown as SourceConfig); } const hasUserStyle = Object.keys(style).length > 0; const hasLayersArray = Array.isArray(style.layers); const popupConfig = kwargs.popup as Record | null; if (sourceType === 'vector' && !hasUserStyle) { // Auto-discovery mode: fetch metadata and add layers for each source layer const prefix = (kwargs.prefix as string) ?? ''; await this.autoDiscoverPMTilesLayers(archiveUrl, layerId, sourceId, opacity, visible, fitBounds, prefix, popupConfig); } else if (hasLayersArray && sourceType === 'vector') { // MapLibre-native style with a "layers" array const layerDefs = style.layers as Array>; const addedLayerIds: string[] = []; // Track all sub-layer IDs (including pre-existing ones) so that // a subsequent remove always cleans up all layers for this group. const allSubLayerIds: string[] = []; for (const layerDef of layerDefs) { const subId = (layerDef.id as string) || `${layerId}-${allSubLayerIds.length}`; allSubLayerIds.push(subId); if (this.map.getLayer(subId)) continue; const subConfig: Record = { ...layerDef, id: subId, source: sourceId, }; // Apply visibility const existingLayout = (layerDef.layout as Record) || {}; subConfig.layout = { ...existingLayout, visibility: visible ? 'visible' : 'none' }; this.map.addLayer(subConfig as maplibregl.AddLayerObject); this.stateManager.addLayer(subId, subConfig as unknown as LayerConfig); this.userOverlayLayerIds.push(subId); addedLayerIds.push(subId); } // Track sub-layers under the parent layerId for removal this.pmtilesSubLayers.set(layerId, allSubLayerIds); // Register popup across all sub-layers if (popupConfig?.enabled && addedLayerIds.length > 0) { this.registerPMTilesGroupPopup(layerId, addedLayerIds, popupConfig); } // Fit bounds if requested if (fitBounds) { const pmtiles = new PMTiles(archiveUrl); pmtiles.getHeader().then(header => { if (this.map) { this.map.fitBounds( [[header.minLon, header.minLat], [header.maxLon, header.maxLat]], { padding: 50, duration: 1000 }, ); } }).catch(err => { console.warn(`[anymap-ts] Could not fetch PMTiles header for fitBounds:`, err); }); } } else if (!this.map.getLayer(layerId)) { // Explicit style mode (existing behavior) let layerConfig: Record; if (sourceType === 'vector') { const layerType = (style.type as string) || 'fill'; // Build paint properties based on layer type let defaultPaint: Record = {}; if (layerType === 'fill') { defaultPaint = { 'fill-color': '#3388ff', 'fill-opacity': opacity, }; } else if (layerType === 'line') { defaultPaint = { 'line-color': '#3388ff', 'line-width': 2, 'line-opacity': opacity, }; } else if (layerType === 'circle') { defaultPaint = { 'circle-color': '#3388ff', 'circle-radius': 5, 'circle-opacity': opacity, }; } else if (layerType === 'symbol') { defaultPaint = { 'text-color': '#3388ff', 'text-opacity': opacity, 'text-halo-color': '#ffffff', 'text-halo-width': 1, }; } // Extract paint and layout properties from style const paintFromStyle: Record = {}; const layoutFromStyle: Record = {}; const layoutKeys = [ 'text-field', 'text-size', 'text-font', 'text-anchor', 'text-offset', 'text-rotate', 'text-max-width', 'text-allow-overlap', 'text-ignore-placement', 'text-justify', 'text-letter-spacing', 'text-line-height', 'text-transform', 'text-padding', 'icon-image', 'icon-size', 'icon-anchor', 'icon-offset', 'icon-rotate', 'icon-allow-overlap', 'icon-ignore-placement', 'icon-padding', 'symbol-placement', 'symbol-spacing', 'symbol-sort-key', ]; for (const [key, value] of Object.entries(style)) { if (key === 'type' || key === 'source-layer' || key === 'filter') continue; if (layoutKeys.includes(key)) { layoutFromStyle[key] = value; } else { paintFromStyle[key] = value; } } // Build layout: default visibility + symbol-specific defaults + user overrides const defaultLayout: Record = { visibility: visible ? 'visible' : 'none', }; if (layerType === 'symbol') { if (!layoutFromStyle['text-field'] && !layoutFromStyle['icon-image']) { defaultLayout['text-field'] = ['get', 'name']; } if (!layoutFromStyle['text-size']) { defaultLayout['text-size'] = 12; } } layerConfig = { id: layerId, type: layerType, source: sourceId, layout: { ...defaultLayout, ...layoutFromStyle }, paint: { ...defaultPaint, ...paintFromStyle }, }; if (style['source-layer']) { layerConfig['source-layer'] = style['source-layer']; } if (style['filter']) { layerConfig['filter'] = style['filter']; } this.map.addLayer(layerConfig as maplibregl.AddLayerObject); if (style['filter'] && (this as any).stateManager) { ((this as any).stateManager as StateManager).setLayerFilter( layerId, style['filter'] as unknown[] | null ); } } else { // Raster PMTiles layerConfig = { id: layerId, type: 'raster', source: sourceId, paint: { 'raster-opacity': opacity, }, layout: { visibility: visible ? 'visible' : 'none', }, }; this.map.addLayer(layerConfig as maplibregl.AddLayerObject); } // Persist layer state for multi-cell rendering this.stateManager.addLayer(layerId, layerConfig as unknown as LayerConfig); // Track as user overlay layer for deck.gl ordering this.userOverlayLayerIds.push(layerId); // Register popup if configured if (popupConfig?.enabled && sourceType === 'vector') { this.registerPMTilesPopup(layerId, layerId, popupConfig); } // Fit bounds if requested if (fitBounds) { const pmtiles = new PMTiles(archiveUrl); pmtiles.getHeader().then(header => { if (this.map) { this.map.fitBounds( [[header.minLon, header.minLat], [header.maxLon, header.maxLat]], { padding: 50, duration: 1000 }, ); } }).catch(err => { console.warn(`[anymap-ts] Could not fetch PMTiles header for fitBounds:`, err); }); } } } catch (error) { console.error(`[anymap-ts] Error adding PMTiles layer "${layerId}":`, error); } } /** * Build paint properties for a given MapLibre layer type. */ private buildPMTilesPaint( layerType: 'fill' | 'line' | 'circle' | 'symbol', color: string, opacity: number, ): Record { if (layerType === 'fill') { return { 'fill-color': color, 'fill-opacity': opacity * 0.6, 'fill-outline-color': color }; } else if (layerType === 'line') { return { 'line-color': color, 'line-width': 2, 'line-opacity': opacity }; } else if (layerType === 'symbol') { return { 'text-color': color, 'text-opacity': opacity, 'text-halo-color': '#ffffff', 'text-halo-width': 1 }; } return { 'circle-color': color, 'circle-radius': 3, 'circle-opacity': opacity, 'circle-stroke-color': color, 'circle-stroke-width': 1, }; } /** * Build layout properties for symbol layers. Symbol layers require layout * properties (text-field, icon-image, etc.) to render. */ private buildPMTilesSymbolLayout( sourceLayerFields: string[], visible: boolean, ): Record { const layout: Record = { visibility: visible ? 'visible' : 'none', 'text-size': 12, 'text-anchor': 'center', 'text-allow-overlap': false, }; // Use the first text-like field name as the label, or fallback to 'name' const textFieldCandidates = ['name', 'label', 'text', 'title', 'description']; let textField = 'name'; for (const candidate of textFieldCandidates) { if (sourceLayerFields.some(f => f.toLowerCase() === candidate)) { textField = sourceLayerFields.find(f => f.toLowerCase() === candidate)!; break; } } layout['text-field'] = ['get', textField]; return layout; } /** * Auto-discover source layers from PMTiles metadata and add MapLibre * layers for each one with a distinct color. When geometry_type is * unknown, adds fill + line + circle sub-layers so all geometries render. */ private async autoDiscoverPMTilesLayers( url: string, layerId: string, sourceId: string, opacity: number, visible: boolean, fitBounds: boolean, prefix: string, popupConfig?: Record | null, ): Promise { if (!this.map) return; const pmtiles = new PMTiles(url); const header = await pmtiles.getHeader(); const metadata = await pmtiles.getMetadata() as Record; // Extract vector_layers from TileJSON metadata const tilestats = metadata.tilestats as Record | undefined; const vectorLayers = ( metadata.vector_layers || (tilestats && tilestats.layers) || [] ) as Array<{ id: string; geometry_type?: string }>; if (vectorLayers.length === 0) { console.warn(`[anymap-ts] No vector_layers found in PMTiles metadata for "${layerId}"`); return; } // Generate distinct colors (one per source layer) const colors = this.generateDistinctColors(vectorLayers.length); // Determine layer type for each source layer. When geometry_type is // known, use it; otherwise infer from the layer name. const layerEntries = vectorLayers.map((vl, i) => ({ vl, color: colors[i], mlType: vl.geometry_type ? this.geometryToLayerType(vl.geometry_type) : this.inferLayerTypeFromName(vl.id), })); // Sort so fill renders first, then line, then circle, then symbol (labels on top) const renderOrder: Record = { fill: 0, line: 1, circle: 2, symbol: 3 }; layerEntries.sort((a, b) => (renderOrder[a.mlType] ?? 0) - (renderOrder[b.mlType] ?? 0)); const subLayerIds: string[] = []; for (const { vl, color, mlType } of layerEntries) { const idBase = prefix ? `${prefix}-${vl.id}` : vl.id; const subLayerId = idBase; // For symbol layers, extract field names from metadata to pick a text-field const vlFields = (vl as Record).fields as Record | undefined; const fieldNames = vlFields ? Object.keys(vlFields) : []; const layerConfig: Record = { id: subLayerId, type: mlType, source: sourceId, 'source-layer': vl.id, layout: mlType === 'symbol' ? this.buildPMTilesSymbolLayout(fieldNames, visible) : { visibility: visible ? 'visible' : 'none' }, paint: this.buildPMTilesPaint(mlType, color, opacity), }; if (!this.map.getLayer(subLayerId)) { this.map.addLayer(layerConfig as maplibregl.AddLayerObject); this.stateManager.addLayer(subLayerId, layerConfig as unknown as LayerConfig); this.userOverlayLayerIds.push(subLayerId); subLayerIds.push(subLayerId); } } // Track sub-layers for removal this.pmtilesSubLayers.set(layerId, subLayerIds); // Register a single grouped popup for all sub-layers if (popupConfig?.enabled) { this.registerPMTilesGroupPopup(layerId, subLayerIds, popupConfig); } // Fit bounds from header if (fitBounds && this.map) { this.map.fitBounds( [[header.minLon, header.minLat], [header.maxLon, header.maxLat]], { padding: 50, duration: 1000 }, ); } // Send discovered layer info (including full style) back to Python this.sendEvent('pmtiles_layers_discovered', { layerId, subLayers: layerEntries.map(({ vl, color, mlType }) => { const idBase = prefix ? `${prefix}-${vl.id}` : vl.id; return { id: idBase, sourceLayer: vl.id, geometryType: vl.geometry_type || 'unknown', color, type: mlType, paint: this.buildPMTilesPaint(mlType, color, opacity), }; }), }); } private handleRemovePMTilesLayer(args: unknown[], kwargs: Record): void { if (!this.map) return; const [layerId] = args as [string]; const sourceId = `${layerId}-source`; // Unregister popup event handlers to prevent accumulation const popupHandlers = this.pmtilesPopupHandlers.get(layerId); if (popupHandlers) { for (const { event, layer, handler } of popupHandlers) { this.map.off(event as 'click' | 'mouseenter' | 'mouseleave', layer, handler as (e: maplibregl.MapLayerMouseEvent) => void); } this.pmtilesPopupHandlers.delete(layerId); } // Check if this was an auto-discovered multi-layer const subLayerIds = this.pmtilesSubLayers.get(layerId); if (subLayerIds) { for (const subId of subLayerIds) { if (this.map.getLayer(subId)) { this.map.removeLayer(subId); this.stateManager.removeLayer(subId); } const idx = this.userOverlayLayerIds.indexOf(subId); if (idx >= 0) this.userOverlayLayerIds.splice(idx, 1); } this.pmtilesSubLayers.delete(layerId); } else { // Single layer (existing behavior) if (this.map.getLayer(layerId)) { this.map.removeLayer(layerId); this.stateManager.removeLayer(layerId); } } if (this.map.getSource(sourceId)) { this.map.removeSource(sourceId); this.stateManager.removeSource(sourceId); } } /** * Escape a string for safe insertion into HTML. */ private escapeHTML(str: string): string { return str .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } /** * Register a click popup for a PMTiles layer. */ private buildPMTilesPopupHTML( props: Record, config: Record, ): string { const properties = config.properties as string[] | undefined; const template = config.template as string | undefined; // Use fully inline styles —