import Map from "ol/Map"; import TileLayer from "ol/layer/Tile"; import { defaults as DefaultControls, ScaleLine, Zoom } from "ol/control"; import View, { ViewOptions } from "ol/View"; import { LolOpenLayersMapProps } from "./LolOpenLayersMap"; import { Cluster, Source, WMTS } from "ol/source"; import XYZSource, { Options as XYZOptions } from "ol/source/XYZ"; import TileSource from "ol/source/Tile"; import VectorTileLayer, { Options as VectorTileLayerOptions, } from "ol/layer/VectorTile"; import VectorTileSource from "ol/source/VectorTile"; import { MVT, WMTSCapabilities } from "ol/format"; import { createXYZ } from "ol/tilegrid"; import { LolOpenLayersMVTSourceDef } from "../sourceDefinition/LolOpenLayersMVTSourceDef"; import { LolOpenLayersVectorTileLayerDef } from "../layerDefinition/LolOpenLayersVectorTileLayerDef"; import VectorLayer from "ol/layer/Vector"; import VectorSource from "ol/source/Vector"; import GeoJSON from "ol/format/GeoJSON"; import { createFeatureCollection, featureMatchByGeometry, HIGHLIGHT_LAYER, } from "./map-utils"; import { LolOpenLayersFeatureSourceDef } from "../sourceDefinition/LolOpenLayersFeatureSourceDef"; import { Geometry, LineString } from "ol/geom"; import { LolOpenLayersVectorLayerDef } from "../layerDefinition/LolOpenLayersVectorLayerDef"; import { ClickedFeature, InternalContextRefType, InternalContextType, LayerState, LolOpenLayersMapContextType, } from "../context/LolOpenLayersMapContext"; import { Feature, MapBrowserEvent, MapEvent, Overlay, VectorTile } from "ol"; import { highlightStyleFunction } from "../style/highlightStyle"; import { IFeatureSource, LolOpenLayersSourceDef, SourceType, } from "../sourceDefinition/LolOpenLayersSourceDef"; import { LayerType, LolOpenLayersLayerDef, } from "../layerDefinition/LolOpenLayersLayerDef"; import { Pixel } from "ol/pixel"; import { Layer } from "ol/layer"; import BaseLayer from "ol/layer/Base"; import { FeatureLike } from "ol/Feature"; import { compact, isEqual, isNil, sortBy, uniqWith } from "lodash-es"; import * as olExtent from "ol/extent"; import { MapLibreLayer } from "@geoblocks/ol-maplibre-layer"; import "./MapLibreWorkerDefault"; import type { StyleSpecification } from "maplibre-gl"; import { optionsFromCapabilities } from "ol/source/WMTS"; import { LolOpenLayersMapLibreSourceDef } from "../sourceDefinition/LolOpenLayersMapLibreSourceDef"; import { LolOpenLayersWMTSSourceDef } from "../sourceDefinition/LolOpenLayersWMTSSourceDef"; import BaseEvent from "ol/events/Event"; import { HighlightedFeatures } from "../model/layerstatus"; import { easeOut } from "ol/easing"; import { DoubleClickZoom, Draw, Modify, Snap } from "ol/interaction"; import { DrawEvent } from "ol/interaction/Draw"; import { Coordinate } from "ol/coordinate"; import Interaction from "ol/interaction/Interaction"; import { ModifyEvent } from "ol/interaction/Modify"; import { LolOpenLayersGeoImageSourceDef } from "../sourceDefinition/LolOpenLayersGeoImageSourceDef"; import ImageLayer from "ol/layer/Image"; import { LolOpenLayersImageLayerDef } from "../layerDefinition/LolOpenLayersImageLayerDef"; import LayerGroup from "ol/layer/Group"; import { updatePlacementOnMove } from "./placement/UpdatePlacement"; import ImageSource from "ol/source/Image"; import { createFeatureStyle, styleWithContext } from "../style/FeatureStyles"; import GeoImage, { Options as GeoImageOptions } from "ol-ext/source/GeoImage"; import { EventsKey } from "ol/events"; import { unByKey } from "ol/Observable"; import Tile from "ol/Tile"; import log from "../utils/Log"; import { loadAndClipFeatures } from "./loadAndClipFeatures"; import { createPlacementParams, PlacementParams, } from "./placement/PlacementParams"; import { loadFeatures } from "../utils/FeatureUtil"; interface GetFeatureAtPixelCallbackParams { feature: FeatureLike; layer: Layer | undefined; } export const createMapFeatures = ( featureData: IFeatureSource[], dataProjection: string | undefined ): Feature[] => { const features = createFeatureCollection(featureData); // Each layer has a projection (datum) - this has been tested // with EPSG:4167 and with EPSG:1 (offset 160) // The feature projection is in metres and is // EPSG:3857 = WGS-84 pseudo mercator throughout return new GeoJSON().readFeatures(features, { dataProjection: dataProjection ?? "EPSG:1", featureProjection: "EPSG:3857", }); }; const zoomToMap = ( map: Map, layerSet: LolOpenLayersLayerDef[], bufferFactor: number ): boolean => { if (!map) return false; log.debug( `MapImplement.zoomToMap, layerSet=${JSON.stringify( layerSet )}, map layers = ${map?.getLayers().getLength()}` ); const zoomFeaturesExtent = olExtent.createEmpty(); map?.getLayers().forEach((layer: BaseLayer) => { const layerName = ( layer as VectorLayer> ).getClassName(); const layerDef = layerSet.find((layerDef) => layerDef.name === layerName); if ( (layer.constructor === VectorLayer && layerSet.length === 0) || (layerDef as LolOpenLayersVectorLayerDef)?.inInitialZoom ) { const vectorLayer = layer as VectorLayer>; const layerExtent = vectorLayer ?.getSource() ?.getExtent() as olExtent.Extent; if (layerExtent) { olExtent.extend(zoomFeaturesExtent, layerExtent); } } }); if (zoomFeaturesExtent[0] === Infinity) { log.debug(`No zoom extent found`); return false; } olExtent.scaleFromCenter(zoomFeaturesExtent, bufferFactor); log.debug(`zoomToMap final extent ${zoomFeaturesExtent}`); map?.getView().fit(zoomFeaturesExtent); return true; }; export type ClickedFeaturesByLayer = Record; export type ClickedLayerFeatures = { ids: number[]; features: FeatureLike[]; }; export interface IMapImplement { setMap: (internalContext: InternalContextRefType) => void; populateOpenlayersMap: ( mapProps: LolOpenLayersMapProps, mapContext: LolOpenLayersMapContextType, internalContext: InternalContextType, setLoading: (state: boolean) => void ) => void; targetZoomControl: () => void; zoomToFit: ( mapContext: LolOpenLayersMapContextType | undefined, internalContext: InternalContextRefType | undefined, layerStatusMap?: Record ) => boolean; updateLayerVisibility: ( mapContext: LolOpenLayersMapContextType | undefined, internalContext: InternalContextRefType | undefined, layerStatusMap?: Record, layerNames?: string[] ) => void; updateSource: ( layerName: string, layerDef: LolOpenLayersLayerDef | undefined, showData: IFeatureSource[] ) => boolean; handleLoading: ( internalContext: InternalContextType, setLoading: (state: boolean) => void ) => void; handleError: (handler: (event: BaseEvent) => void) => void; handleMoveStart: (internalContext: InternalContextType) => void; handleMoveEnd: ( mapContext: LolOpenLayersMapContextType | undefined, internalContext: InternalContextType ) => void; handleClick: (internalContext: InternalContextType) => void; handleRightClick: (internalContext: InternalContextType) => void; handleDrawStart: (internalContext: InternalContextType) => void; handleDrawEnd: (internalContext: InternalContextType) => void; handleSnap: () => void; handleModifyStart: (internalContext: InternalContextType) => void; handleModifyEnd: (internalContext: InternalContextType) => void; unHandleAll: () => void; setTargetRef: (ref: React.MutableRefObject) => void; copySelectionsToHighlightLayer: ( allSelectedFeaturesByPanel: HighlightedFeatures[] | null, mapContext: LolOpenLayersMapContextType ) => void; zoomMapByDelta: (delta: number) => void; getFeaturesAtPixel: ( pixel: Pixel, hitTolerancePixels?: number ) => ClickedFeature[]; getFeaturesAtPixelOrderedByClosestToClick: ( pixelCoordinates: Pixel, hitTolerancePixels: number, includeLayerNames?: string[] ) => ClickedFeaturesByLayer; findMapLayerByName: (layerName: string) => BaseLayer | undefined; loadChangedFeaturesFrom: ( layerName: string, layerDef: LolOpenLayersLayerDef | undefined, featureData: IFeatureSource[] | string | GeoImage ) => void; layerChanged: (layerName: string) => void; labelLayerChanged: (layerName: string, underlyingLayerDone?: boolean) => void; layerNames: () => string[]; layerDefs: () => Record; getConfig: () => LolOpenLayersMapProps | undefined; getUnclippedFeatures: (layerName: string) => IFeatureSource[]; getPlacementParams: () => PlacementParams | undefined; } export const FEATURE_PIXEL_TOLERANCE = 5; let drawLayerSource: VectorSource | undefined; let modifyLayerSource: VectorSource | undefined; export class MapImplement implements IMapImplement { private mapProps?: LolOpenLayersMapProps; private activeHandlers: Set = new Set(); private withInitialZoom = false; unclippedFeatures: Record = {}; private createOpenLayersMap = () => { return new Map({ controls: DefaultControls({ zoom: false }).extend([new ScaleLine()]), }); }; private map = this.createOpenLayersMap(); private drawInteraction: any; private modifyInteraction: any; private snapInteraction: any; private wmtsCapabilityParser = new WMTSCapabilities(); setMap = (internalContext: InternalContextRefType) => { internalContext.setMap(this.map); internalContext.setMapImplement(this); }; private createMVTSource = (sourceDef: LolOpenLayersSourceDef) => { const xyzTileGrid = createXYZ({ minZoom: (sourceDef as LolOpenLayersMVTSourceDef).minZoom, maxZoom: sourceDef.maxZoom, }); // Override defaultLoadFunction() in ol/VectorTile to use our custom feature loader const tileLoadFunction = (tile: Tile, url: string) => { const vectorTile = tile as VectorTile; vectorTile.setLoader((extent, _resolution, projection) => { loadFeatures(url, vectorTile.getFormat(), extent, projection).then( (features) => { vectorTile.setFeatures(features as Feature[]); } ); }); }; return new VectorTileSource({ url: (sourceDef as LolOpenLayersMVTSourceDef).url, tileLoadFunction, format: new MVT({ idProperty: (sourceDef as LolOpenLayersMVTSourceDef).idProperty, }), wrapX: true, tileGrid: xyzTileGrid, minZoom: (sourceDef as LolOpenLayersMVTSourceDef).minZoom, maxZoom: (sourceDef as LolOpenLayersMVTSourceDef).maxZoom, }); }; private createGeoImageSource = (sourceDef: LolOpenLayersSourceDef) => { return new GeoImage({ url: (sourceDef as LolOpenLayersGeoImageSourceDef).url, imageCenter: (sourceDef as LolOpenLayersGeoImageSourceDef).imageCenter, imageScale: (sourceDef as LolOpenLayersGeoImageSourceDef).imageScale ?? [ 1, 1, ], imageRotate: (sourceDef as LolOpenLayersGeoImageSourceDef).imageRotate ?? 0, imageMask: undefined as unknown as Coordinate[], } as GeoImageOptions); }; private createVectorSource( layerDef: LolOpenLayersVectorLayerDef, mapContext: LolOpenLayersMapContextType ) { const sourceDef = layerDef.source as LolOpenLayersFeatureSourceDef; let underlyingSource = sourceDef.wrapSource; if (!underlyingSource) { const layerFeatureData = mapContext.featureData(layerDef.name); let featureData = sourceDef.data || sourceDef.query?.data || (typeof layerFeatureData !== "string" && (layerFeatureData as IFeatureSource[])) || []; featureData = layerDef.featureFilter?.(featureData) ?? featureData; log.debug( `createVectorSource::Loading ${ layerDef.name } from ${sourceDef}, featureData=${JSON.stringify(featureData)}` ); this.unclippedFeatures[layerDef.name] = [...featureData]; const loadedFeatures = createMapFeatures( featureData, sourceDef.projection ); underlyingSource = new VectorSource({ features: loadedFeatures, }); } if (!sourceDef.cluster) return underlyingSource; return new Cluster({ ...sourceDef.cluster, source: underlyingSource }); } private openlayersSource = ( layerDef: LolOpenLayersLayerDef, mapContext: LolOpenLayersMapContextType ): Source => { const sourceDef = layerDef.source; let source; switch (sourceDef.type) { case SourceType.XYZ: source = new XYZSource(sourceDef as XYZOptions); break; case SourceType.MVT: source = this.createMVTSource(sourceDef); break; case SourceType.FEATURES: source = this.createVectorSource( layerDef as LolOpenLayersVectorLayerDef, mapContext ); break; case SourceType.GEOIMAGE: source = this.createGeoImageSource(sourceDef); break; default: throw new Error(`Unexpected source type ${sourceDef.type}`); } source.addEventListener("tileloaderror", () => { const message = `Failed to load source for ${layerDef.name}`; if (!mapContext.errorMessages.includes(message)) { mapContext.errorMessages.push(message); } }); return source; }; private createVectorLayer = ( layerDef: LolOpenLayersVectorLayerDef, mapContext: LolOpenLayersMapContextType, internalContext: InternalContextType, placementEnabled: boolean ) => { log.debug(`DEBUG: createVectorLayer ${JSON.stringify(layerDef)}`); if (layerDef.clipFeatures) { log.debug(`DEBUG: clipfeatures add ${layerDef.name}`); internalContext.ref()?.enableClipFeatureLayers()?.add(layerDef.name); } const baseStyle = layerDef.style; const highlightStyle = layerDef.highlightStyle; return new VectorLayer({ className: layerDef.name, zIndex: layerDef.zIndex, minResolution: layerDef.minResolution, maxResolution: layerDef.maxResolution, minZoom: layerDef.minZoom, maxZoom: layerDef.maxZoom, source: this.openlayersSource( layerDef, mapContext ) as VectorSource, style: createFeatureStyle( highlightStyle, () => mapContext?.getStyleContext(layerDef.name), internalContext, baseStyle ), visible: layerDef.visible, declutter: layerDef.declutter, properties: { geometrySizeForClickDetection: layerDef.geometrySizeForClickDetection, }, // If placement is enabled, we want a larger buffer so that labels // can be placed off screen and moved on by offset renderBuffer: placementEnabled ? 2048 : 100, }); }; private createVectorTileLayer = ( layerDef: LolOpenLayersLayerDef, mapContext: LolOpenLayersMapContextType, internalContext: InternalContextType ) => new VectorTileLayer({ className: layerDef.name, zIndex: layerDef.zIndex, minResolution: layerDef.minResolution, maxResolution: layerDef.maxResolution, minZoom: layerDef.minZoom, maxZoom: layerDef.maxZoom, source: this.openlayersSource( layerDef as LolOpenLayersVectorLayerDef, mapContext ) as VectorTileSource, style: createFeatureStyle( (layerDef as LolOpenLayersVectorTileLayerDef).highlightStyle, () => mapContext?.getStyleContext(layerDef.name), internalContext, (layerDef as LolOpenLayersVectorTileLayerDef).style ), visible: this.isVisibleAtStart(layerDef), renderMode: (layerDef as LolOpenLayersVectorTileLayerDef).renderMode ?? "hybrid", declutter: (layerDef as LolOpenLayersVectorTileLayerDef).declutter ?? false, properties: { geometrySizeForClickDetection: layerDef.geometrySizeForClickDetection, }, } as VectorTileLayerOptions); private createImageLayer = ( layerDef: LolOpenLayersLayerDef, mapContext: LolOpenLayersMapContextType ) => new ImageLayer({ className: layerDef.name, source: this.openlayersSource( layerDef as LolOpenLayersImageLayerDef, mapContext ) as ImageSource, visible: layerDef.visible ?? true, opacity: layerDef.opacity ?? 1.0, }); populateOpenlayersMap = ( mapProps: LolOpenLayersMapProps, mapContext: LolOpenLayersMapContextType, internalContext: InternalContextType, setLoading: (state: boolean) => void ) => { log.debug(`DEBUG: populateOpenlayersMap`); this.mapProps = mapProps; if (this.mapProps.disableDoubleClickZoom) { const dblClickZoomInteractions = this.map .getInteractions() .getArray() .filter((interaction) => { return interaction instanceof DoubleClickZoom; }); if (dblClickZoomInteractions.length > 0) { dblClickZoomInteractions.forEach((dblClickZoomInteraction) => { this.map.removeInteraction(dblClickZoomInteraction); }); } } else { /** Add interaction*/ const doubleClickZoom = new DoubleClickZoom({}); this.addMapInteraction(doubleClickZoom); } /*** * Add layer group */ const layersInGroup = this.mapProps.layerGroup?.layers ?? []; const layerGroupClassName = this.mapProps.layerGroup?.className ?? "layerGroup"; const allLayersInGroup = this.compactAllLayers( layersInGroup, setLoading, internalContext, mapContext, mapProps.enableAutoPlacement ?? false ); this.withInitialZoom = this.mapProps.layers.some( (l) => (l as LolOpenLayersVectorLayerDef).inInitialZoom ); const layerGroup = new LayerGroup({ layers: allLayersInGroup, properties: { className: layerGroupClassName }, }); // Display the map in the div with the id of map this.map?.setTarget(undefined); const layers = this.compactAllLayers( mapProps.layers, setLoading, internalContext, mapContext, mapProps.enableAutoPlacement ?? false ).concat( new VectorLayer({ className: HIGHLIGHT_LAYER, source: new VectorSource(), style: highlightStyleFunction, zIndex: 100, }) ); this.map?.setLayers(layers); /** Add layer group to all layers and keep it as its own layers level */ this.map?.addLayer(layerGroup); // Render the tile layers in a map view with a Mercator projection this.map?.setView(new View(mapProps.view as ViewOptions)); this.map?.updateSize(); if (mapProps.withOverlay) { const overlayElement = document.createElement("div"); overlayElement.classList.add("surveyMapInfoOverlay"); // Note that consumer in surveyMap doesn't like integer ids const overlay = new Overlay({ id: "default", element: overlayElement, autoPan: {}, }); this.map?.addOverlay(overlay); internalContext?.ref()?.setOverlay(overlay); } else { const overlay = this.map?.getOverlayById(100); if (overlay) this.map?.removeOverlay(overlay); } }; /*** * Compact the layers * @param layers * @param setLoading * @param internalContext * @param mapContext * @param enableAutoPlacement true if we have autoplacement enabled * @private */ private compactAllLayers( layers: LolOpenLayersLayerDef[], setLoading: (state: boolean) => void, internalContext: InternalContextType, mapContext: LolOpenLayersMapContextType, enableAutoPlacement: boolean ): ( | TileLayer | VectorTileLayer | VectorLayer> | Layer )[] { return compact( layers.flatMap((layerDef: LolOpenLayersLayerDef, layerIndex) => { switch (layerDef.type) { case LayerType.TILE: // where the layer creates asynchronously, put it where it would // otherwise be in the layers stack const layerBeforeIndex = layerIndex; if (layerDef.source.type === SourceType.MAP_LIBRE) { const fetchPromise = fetch( (layerDef.source as LolOpenLayersMapLibreSourceDef).url ); fetchPromise .then((styleData) => { return styleData.json(); }) .then((styleJson: StyleSpecification) => { const layerDefSource = layerDef.source as LolOpenLayersMapLibreSourceDef; const layersToExclude = layerDefSource?.excludeLayers && layerDefSource.excludeLayers.length !== 0 ? layerDefSource.excludeLayers : []; styleJson.layers = styleJson.layers // take out any that have been added to exclude list .filter( (l: { id: string }) => !layersToExclude.includes(l.id) ); const newLayer = new MapLibreLayer({ minResolution: layerDef.minResolution, maxResolution: layerDef.maxResolution, mapLibreOptions: { style: styleJson, maxZoom: layerDefSource.maxZoom, // allows exporting canvas to png canvasContextAttributes: { preserveDrawingBuffer: layerDefSource?.preserveDrawingBuffer, }, }, // This is just used to set the attributions source: new VectorTileSource({ attributions: layerDefSource.attributions ?? "© 2022 Toitū Te Whenua - CC BY 4.0", }), className: layerDef.name, visible: this.isVisibleAtStart(layerDef), zIndex: layerDef.zIndex, }); this.map.getLayers().insertAt(layerBeforeIndex, newLayer); setLoading(true); internalContext.ref()?.inContext() && internalContext.ref()?.setLoading(true); }) .catch((e) => { const message = `Error ${e} loading MapLibre layer`; mapContext.errorMessages.push(message); console.error(message); }); return null; } if (layerDef.source.type === SourceType.WMTS) { const fetchPromise = fetch( (layerDef.source as LolOpenLayersWMTSSourceDef).url ); fetchPromise .then((response) => { return response.text(); }) .then((capabilitiesStr) => { const capabilities = this.wmtsCapabilityParser.read(capabilitiesStr); const options = optionsFromCapabilities(capabilities, { layer: "aerial", matrixSet: "EPSG:3857", }); const newLayer = new TileLayer({ source: new WMTS(options!!), className: layerDef.name, visible: this.isVisibleAtStart(layerDef), zIndex: layerDef.zIndex, }); this.map.getLayers().insertAt(layerBeforeIndex, newLayer); setLoading(true); internalContext.ref()?.inContext() && internalContext.ref()?.setLoading(true); }) .catch((e) => { const message = `Error ${e} loading WMTS layer`; mapContext.errorMessages.push(message); console.error(message); }); return null; } return new TileLayer({ className: layerDef.name, zIndex: layerDef.zIndex, minResolution: layerDef.minResolution, maxResolution: layerDef.maxResolution, minZoom: layerDef.minZoom, maxZoom: layerDef.maxZoom, visible: false, source: this.openlayersSource( layerDef as LolOpenLayersVectorLayerDef, mapContext ) as TileSource, }); case LayerType.VECTOR_TILE: if ((layerDef as LolOpenLayersVectorTileLayerDef).labelStyle) { return [ this.createVectorTileLayer( layerDef, mapContext, internalContext ), new VectorTileLayer({ className: `${layerDef.name}_labels`, zIndex: layerDef.zIndex ? layerDef.zIndex + 10 : undefined, minResolution: layerDef.minResolution, maxResolution: layerDef.maxResolution, minZoom: layerDef.minZoom, maxZoom: layerDef.maxZoom, visible: this.isVisibleAtStart(layerDef), source: this.openlayersSource( layerDef, mapContext ) as VectorTileSource, style: styleWithContext( `TILE: ${layerDef.name}_labels`, (layerDef as LolOpenLayersVectorLayerDef).labelStyle, mapContext, internalContext, layerDef.name ), renderMode: "vector", declutter: (layerDef as LolOpenLayersVectorTileLayerDef) .declutterLabels ?? (layerDef as LolOpenLayersVectorTileLayerDef).declutter ?? false, properties: { geometrySizeForClickDetection: layerDef.geometrySizeForClickDetection, }, }), ]; } return this.createVectorTileLayer( layerDef, mapContext, internalContext ); case LayerType.VECTOR: if ((layerDef as LolOpenLayersVectorLayerDef).labelStyle) { const labelLayerName = `${layerDef.name}_labels`; return [ this.createVectorLayer( layerDef as LolOpenLayersVectorLayerDef, mapContext, internalContext, enableAutoPlacement ), new VectorLayer({ className: labelLayerName, zIndex: layerDef.zIndex ? layerDef.zIndex + 10 : undefined, minResolution: layerDef.minResolution, maxResolution: layerDef.maxResolution, minZoom: layerDef.minZoom, maxZoom: layerDef.maxZoom, source: this.openlayersSource( layerDef, mapContext ) as VectorSource, // The styler function is called with the same mapContext.getStyleContext // as the base layer style: styleWithContext( `VECTOR: ${layerDef.name}_labels`, (layerDef as LolOpenLayersVectorLayerDef).labelStyle, mapContext, internalContext, layerDef.name ), visible: true, declutter: (layerDef as LolOpenLayersVectorLayerDef).declutterLabels ?? !enableAutoPlacement, // If placement is enabled, we want a larger buffer so that labels // can be placed off-screen and moved on by offset renderBuffer: enableAutoPlacement ? 2048 : 100, properties: { geometrySizeForClickDetection: layerDef.geometrySizeForClickDetection, }, }), ]; } return this.createVectorLayer( layerDef as LolOpenLayersVectorLayerDef, mapContext, internalContext, enableAutoPlacement ); case LayerType.IMAGE: return this.createImageLayer(layerDef, mapContext); default: const message = `Don't know how to handle layer type: ${layerDef.type}`; mapContext.errorMessages.push(message); throw new Error(message); } }) ); } targetZoomControl = () => { const zoomControl = new Zoom(); zoomControl.setTarget("zoom-buttons"); this.map.addControl(zoomControl); }; /** * Return each feature, and the layer it was found on, that matches where the user clicked. */ getFeaturesAtPixel = ( pixel: Pixel, hitTolerancePixels: number = FEATURE_PIXEL_TOLERANCE ): ClickedFeature[] => { const foundFeatures: ClickedFeature[] = []; const featuresAtPixel: GetFeatureAtPixelCallbackParams[] = []; // forEachFeatureAtPixel is not re-entrant and the callback uses it, // so pre-read the values before callback is called this.map.forEachFeatureAtPixel( pixel, (feature: FeatureLike, layer: Layer | undefined) => { featuresAtPixel.push({ feature, layer }); }, { hitTolerance: hitTolerancePixels } ); featuresAtPixel.forEach( ({ feature, layer }: GetFeatureAtPixelCallbackParams) => { const layerName = layer?.getClassName(); if (!layer || !layerName || layerName === HIGHLIGHT_LAYER) return; // Allow clicks to be disabled on a layer const layerDef = this.findLayerDefByName(layerName); if (layerDef?.disableClicks) return; const { geometrySizeForClickDetection } = layer.getProperties(); if (geometrySizeForClickDetection == null) { foundFeatures.push({ feature, layer, distance: 0 }); } else { const distance = featureMatchByGeometry( this.map, pixel, geometrySizeForClickDetection, feature ); if (distance != null) { foundFeatures.push({ feature, layer, distance }); } } } ); // sort feature by distance to click, otherwise by id return sortBy( // OpenLayers can return the same render feature more than once when it is // in multiple overlapped tiles. uniqWith(foundFeatures, (a, b) => isEqual(a.feature.getProperties(), b.feature.getProperties()) ), [(f) => f.distance, (f) => f.feature.get("id")] ) as ClickedFeature[]; }; zoomToFit = ( mapContext: LolOpenLayersMapContextType | undefined, internalContext: InternalContextRefType | undefined, layerStatusMap?: Record ): boolean => { const map = this.map; if (!this.mapProps?.layers) throw new Error("MapImplement::zoomToFit with no layers configured"); const zoomRes = zoomToMap( map, this.mapProps.layers, this.mapProps?.bufferFactor ?? 1.05 ); log.debug("mapImplement.zoomToFit calls updateLayerVisibility"); this.updateLayerVisibility(mapContext, internalContext, layerStatusMap); return zoomRes; }; baseLayerName = (layer: BaseLayer) => layer.getClassName().replace(RegExp("_labels$"), ""); updateLayerVisibility = ( mapContext: LolOpenLayersMapContextType | undefined, internalContext: InternalContextRefType | undefined, layerStatusMap?: Record, layerNames?: string[] ): void => { log.debug(`+++updateLayerVisibility ${layerNames}`); this.map?.getLayers().forEach((layer: BaseLayer) => { const layerName = layer.getClassName(); if (!layerNames || layerNames.includes(layerName)) { if (layerName.endsWith("_labels")) { const baseLayerName = this.baseLayerName(layer); const baseLayerDef = this.findLayerDefByName(baseLayerName); if (baseLayerDef) { const contextlayerStatus = mapContext ? mapContext.layerStatus(baseLayerName) : layerStatusMap?.[baseLayerName]?.status; const labelsChecked = (contextlayerStatus?.layerLabelsChecked || contextlayerStatus?.layerBadgesChecked) ?? baseLayerDef?.visible ?? true; log.debug( `MapImplement set layerName=${layerName} labelsChecked = ${labelsChecked}` ); const layerVisible = (internalContext?.zoomed() || this.isVisibleAtStart(baseLayerDef)) && (contextlayerStatus?.layerVisibility ?? this.findLayerDefByName(baseLayerName)?.visible ?? true); if (layer.getVisible() !== (labelsChecked && layerVisible)) { layer.setVisible(labelsChecked && !!layerVisible); layer.changed(); } if (contextlayerStatus && contextlayerStatus.layerZIndex) { layer.setZIndex(contextlayerStatus.layerZIndex + 10); } } } else { const contextlayerStatus = mapContext ? mapContext.layerStatus(layerName) : layerStatusMap?.[layerName]?.status; const layerDef = this.findLayerDefByName(layerName); if (layerDef) { let layerChanged = false; const layerVisible = (internalContext?.zoomed() || this.isVisibleAtStart(layerDef)) && (contextlayerStatus?.layerVisibility ?? this.findLayerDefByName(layerName)?.visible ?? true); if (layer.getVisible() !== layerVisible) { layer.setVisible(!!layerVisible); layerChanged = true; } const layerOpacity = contextlayerStatus?.layerOpacity; if (layerOpacity != null && layer.getOpacity() !== layerOpacity) { layer.setOpacity(layerOpacity); layerChanged = true; } const layerZIndex = contextlayerStatus?.layerZIndex; if (layer.getZIndex() !== layerZIndex) { layer.setZIndex(layerZIndex ?? 0); layerChanged = true; } layerChanged && layer.changed(); } } } }); log.debug("---updateLayerVisibility"); }; findMapLayerByName = (layerName: string) => this.map ?.getLayers() .getArray() .find((mapLayer) => mapLayer.getClassName() === layerName); updateSource = ( layerName: string, layerDef: LolOpenLayersLayerDef | undefined, result: IFeatureSource[] ) => { const source = ( this.findMapLayerByName(layerName) as VectorLayer> )?.getSource(); if (!(source && result)) return false; source.clear(); source.addFeatures(createMapFeatures(result, layerDef?.source?.projection)); return true; }; handleLoading = ( internalContext: InternalContextType, setLoading: (state: boolean) => void ) => { let pendingCount = 0; const setLoadingState = (loading: boolean) => { setLoading(loading); internalContext.ref()?.inContext() && internalContext.ref()?.setLoading(loading); }; const increment = () => { pendingCount++; setLoadingState(true); }; const decrement = () => { pendingCount = Math.max(0, pendingCount - 1); if (pendingCount === 0) setLoadingState(false); }; // Safety net — rendercomplete is ground truth if counts drift const renderCompleteKey = this.map.on("rendercomplete", () => { pendingCount = 0; setLoadingState(false); const res = this.map.getView().getResolution(); if (res) { internalContext.ref()?.inContext() && internalContext.ref()?.setMapResolution(res); } }); this.activeHandlers.add(renderCompleteKey); const registerLayerListeners = (layer: BaseLayer) => { const source = (layer as any).getSource?.(); if (!source) return; if (layer instanceof VectorTileLayer || layer instanceof TileLayer) { source.on("tileloadstart", increment); source.on("tileloadend", decrement); source.on("tileloaderror", decrement); } else if (layer instanceof VectorLayer) { source.on("featuresloadstart", increment); source.on("featuresloadend", decrement); source.on("featuresloaderror", decrement); } }; this.map.getLayers().getArray().forEach(registerLayerListeners); const layerAddKey = this.map .getLayers() .on("add", (e) => registerLayerListeners(e.element)); this.activeHandlers.add(layerAddKey as EventsKey); }; handleError = (handler: (event: BaseEvent) => void) => { this.activeHandlers.add(this.map.on("error", handler)); }; handleMoveStart = (internalContext: InternalContextType): void => { const moveStartHandler = () => { if (internalContext.ref()?.enableAutoPlacement()) { internalContext.ref()?.setPlacementInProgress(true); } }; this.activeHandlers.add(this.map.on("movestart", moveStartHandler)); }; handleMoveEnd = ( mapContext: LolOpenLayersMapContextType | undefined, internalContext: InternalContextType ): void => { const moveEndHandler = (event: MapEvent) => { const mapSizePixels = event.map.getSize(); const mapExtent = event.map.getView().calculateExtent(mapSizePixels); const bl = olExtent.getBottomLeft(mapExtent); const tr = olExtent.getTopRight(mapExtent); const zoom = event.map.getView().getZoom(); const maxZoom = this.mapProps?.view?.maxZoom ?? 30; if (mapSizePixels) { internalContext.ref()?.inContext() && internalContext.ref()?.onMove?.([bl, tr], mapSizePixels); } if ( mapContext && mapSizePixels && internalContext.ref()?.enableAutoPlacement() ) { updatePlacementOnMove(internalContext, this.getPlacementParams()); } if ((internalContext.ref()?.enableClipFeatureLayers()?.size ?? 0) > 0) { loadAndClipFeatures(this, internalContext, bl, tr); } // Because setting the maxZoom on map creation rounds the value, and some // underlying data disappears on zoom 30, the map setZoom() function is // used to set the zoom to 29.99 on moveend event, if it reached a zoom // of 30 or more if (!isNil(zoom) && zoom >= maxZoom) { this.map.getView().setZoom(maxZoom - 0.01); } }; this.activeHandlers.add(this.map.on("moveend", moveEndHandler)); }; handleClick = (internalContext: InternalContextType) => { log.debug( `DEBUG: mapImplement.handleClick listeners = ${ this.map.getListeners("click")?.length }` ); const clickHandler = (event: MapBrowserEvent) => { if (internalContext.ref()?.inContext()) { log.debug( `DEBUG: clickHandler listeners = ${ this.map.getListeners("click")?.length }=> ${this.map.getListeners("click")} ${JSON.stringify( event.pixel )} on ${event.target?.tagName} ${event.target?.id} original: ${ event.originalEvent?.timeStamp } ${ event.originalEvent?.target?.tagName } ${event.originalEvent?.target?.id} parent class: ${ event.originalEvent?.target?.parentElement?.className } currentTarget: ${event.originalEvent?.currentTarget?.tagName} ${event.originalEvent?.currentTarget?.id} parent class: ${ event.originalEvent?.currentTarget?.parentElement?.className }` ); internalContext?.ref()?.onClick?.(event.pixel, event.coordinate, this); // This event will propagate to any `map.on` handlers } }; this.activeHandlers.add(this.map.on("click", clickHandler)); }; addMapInteraction = (interaction: Interaction) => { this.map.addInteraction(interaction); }; handleRemoveMapInteraction = (internalContext: InternalContextType) => { if (!internalContext.ref()?.inContext()) return; if (internalContext.ref()?.onRemoveInteraction) { let remove = internalContext.ref()?.onRemoveInteraction; let drawInteraction = this.mapProps?.drawInteraction; let snapInteraction = this.mapProps?.snapInteraction; if (remove) { if (drawInteraction && this.drawInteraction) { this.map.removeInteraction(this.drawInteraction); } if (snapInteraction && this.snapInteraction) { this.map.removeInteraction(this.snapInteraction); } } } }; handleDrawStart = (internalContext: InternalContextType) => { if (!internalContext.ref()?.inContext()) return; /** * Not passed layer name, not add draw interaction. */ let drawInteractionConfig = this.mapProps?.drawInteraction; let checkDrawInteraction = drawInteractionConfig && drawInteractionConfig?.layerName !== undefined; if (!checkDrawInteraction) return; const layerName = drawInteractionConfig?.layerName; const geometryType = drawInteractionConfig?.geometryType; /** * open layer draw interaction */ if (layerName) { let source = ( this.findMapLayerByName(layerName) as VectorLayer< VectorSource > )?.getSource(); if (source) drawLayerSource = source; } this.drawInteraction = new Draw({ condition: drawInteractionConfig?.condition, source: drawLayerSource ?? undefined, type: geometryType ?? "LineString", // Default as line string finishCondition: drawInteractionConfig?.finishCondition, stopClick: true, dragVertexDelay: 100, }); this.addMapInteraction(this.drawInteraction); if (this.drawInteraction) { const drawStartHandler = (event: DrawEvent) => { const feature = event.feature as Feature; const selectedCoord = feature .getGeometry() ?.getCoordinates()[0] as Coordinate; if (!selectedCoord) { this.drawInteraction.abortDrawing(); } }; this.activeHandlers.add( this.drawInteraction.on("drawstart", drawStartHandler) ); } }; handleDrawEnd = (internalContext: InternalContextType) => { if (this.drawInteraction) { const drawEndHandler = (event: DrawEvent) => { if (!internalContext.ref()?.inContext()) return; // feature const drawFeature = event.feature as Feature; if (drawFeature) { /** * Pass draw feature for draw end callback */ internalContext.ref()?.onDrawEnd?.(drawFeature); /** After draw end then remove interactions */ this.handleRemoveMapInteraction(internalContext); } }; this.activeHandlers.add( this.drawInteraction.on("drawend", drawEndHandler) ); } }; handleSnap = () => { /** * Not passed layer name, not add snap interaction. */ let snap = this.mapProps?.snapInteraction; if (snap === undefined) return; const layerName = snap.layerName; let tolerance = snap.pixelTolerance; let snapSource; if (layerName) { snapSource = ( this.findMapLayerByName(layerName) as VectorLayer< VectorSource > )?.getSource() ?? undefined; } this.snapInteraction = new Snap({ source: snapSource, pixelTolerance: tolerance, }); this.map.addInteraction(this.snapInteraction); }; /** Handle modify interaction */ handleModifyStart = (internalContext: InternalContextType) => { /** Check wheather to start modify interaction */ if (!internalContext.ref()?.inContext()) return; /** * If no passed layer name, then not to add modify interaction. */ const modifyInteractionConfig = this.mapProps?.modifyInteraction; let checkModifyInteraction = modifyInteractionConfig && modifyInteractionConfig?.layerName !== undefined; if (!checkModifyInteraction) return; let layerName = modifyInteractionConfig?.layerName; if (layerName) { let source = ( this.findMapLayerByName(layerName) as VectorLayer< VectorSource > )?.getSource(); if (source) modifyLayerSource = source; } this.modifyInteraction = new Modify({ condition: modifyInteractionConfig?.condition, source: modifyLayerSource ?? undefined, }); /** Add interaction first, then modify */ this.addMapInteraction(this.modifyInteraction); if (this.modifyInteraction) { const modifyStartHandler = (event: ModifyEvent) => { const features = event.features.getArray() as Feature[]; if (features) { internalContext.ref()?.onModifyStart?.(features); } }; this.activeHandlers.add( this.modifyInteraction.on("modifystart", modifyStartHandler) ); } }; handleModifyEnd = (internalContext: InternalContextType) => { if (this.modifyInteraction) { const modifyEndHandler = (event: ModifyEvent) => { if (!internalContext.ref()?.inContext()) return; // features const features = event.features.getArray() as Feature[]; if (features) { /** Pass callback event features to internal context */ internalContext.ref()?.onModifyEnd?.(features); /** Remove interactions from the map */ this.handleRemoveMapInteraction(internalContext); } }; this.activeHandlers.add( this.modifyInteraction.on("modifyend", modifyEndHandler) ); } }; handleRightClick = (internalContext: InternalContextType) => { const contextMenuHandler = (event: MapBrowserEvent) => { this.handleShowContextMenu(internalContext, event); }; // The contextmenu event is from default html dom, not from openlayer MapEvent. // The openlayer MapEvent not have contextmenu or right click event methods yet. // @ts-ignore this.activeHandlers.add(this.map.on("contextmenu", contextMenuHandler)); }; handleShowContextMenu = ( internalContext: InternalContextType, event: MapBrowserEvent ) => { event.preventDefault(); let anchorPoint = { x: event.originalEvent.clientX, y: event.originalEvent.clientY, }; if (!internalContext.ref()?.inContext()) return; const clickedFeatures = this.getFeaturesAtPixel(event.pixel); internalContext .ref() ?.onContextMenu?.(clickedFeatures, event.coordinate, anchorPoint); }; setTargetRef = (ref: React.MutableRefObject) => { this.map.setTarget(ref.current || undefined); }; unHandleAll = () => { this.activeHandlers.forEach((eventKey) => { log.debug(`DEBUG: Drop handler for ${eventKey.type}`); unByKey(eventKey); }); this.activeHandlers = new Set(); }; // The logic to highlight selections based on the allSelectedFeaturesByPanel object // which lists features to be highlighted // We can highlight features by overlaying them in the highlight layer // or by changing their style. The latter is needed for VectorTilesLayer as // the highlight layer method results in artefacts when rendered. // Select features from all VectorLayers by overlaying with a same-sized feature in // the highlight layer. copySelectionsToHighlightLayer = ( allSelectedFeaturesByPanel: HighlightedFeatures[] | null, mapContext: LolOpenLayersMapContextType ): void => { if (!allSelectedFeaturesByPanel) return; const highlightLayer = this.findMapLayerByName( HIGHLIGHT_LAYER ) as VectorLayer>; if (!highlightLayer) return; highlightLayer.getSource()?.clear(); this.map.getLayers().forEach((layer) => { allSelectedFeaturesByPanel?.forEach(({ layerName, selectedFeatures }) => { const layerDef = this.mapProps?.layers?.find( (l) => l.name === layerName ); if ( (mapContext.layerStatus(layerName)?.layerVisibility ?? layerDef?.visible ?? true) && layer.getClassName() === layerName && layer instanceof VectorLayer ) { layer .getSource() .getFeatures() .forEach((f: Feature) => { log.debug(`Highlight feature ${JSON.stringify(f)}`); if ( selectedFeatures.includes(f.get("id")) && !highlightLayer.getSource()?.hasFeature(f) ) { highlightLayer.getSource()?.addFeature(f); } }); } }); }); }; zoomMapByDelta = (delta: number) => { const view = this.map.getView(); if (!view) return; const currentZoom = view.getZoom(); if (currentZoom === undefined) return; const newZoom = view.getConstrainedZoom(currentZoom + delta); view.getAnimating() && view.cancelAnimations(); view.animate({ zoom: newZoom, duration: 250, easing: easeOut }); }; /** * Gets a map of the closest feature (features if multiple equidistant features) to clicked pixel for each layer. * Result is in a map of layerName to featureIds. * * @param pixelCoordinates Pixel to search from. * @param hitTolerancePixels Maximum pixel radius to search. * @param includeLayerNames If present, only include listed layers * * @return Map of layerName to sorted featureIds. */ getFeaturesAtPixelOrderedByClosestToClick = ( pixelCoordinates: Pixel, hitTolerancePixels: number = FEATURE_PIXEL_TOLERANCE, includeLayerNames?: string[] ): ClickedFeaturesByLayer => { const result: ClickedFeaturesByLayer = {}; // This works by calling getFeaturesFromClick for an ever-increasing search radius // adding new featureIds as they are found. This makes sure the closest features are returned first. const layerAlreadyPopulated = new Set(); for (let ht = 1; ht <= hitTolerancePixels; ht++) { const layerNextPopulated = new Set(); this.getFeaturesAtPixel(pixelCoordinates, ht).forEach((f) => { if (!f.layer) return; // We can click features that don't have a layer (?) const layerName = f.layer.getClassName(); if (layerAlreadyPopulated.has(layerName)) return; if (includeLayerNames && !includeLayerNames.includes(layerName)) return; // If feature is not in list for layer, then append it to the end of featureIds const id = f.feature.getId() ?? f.feature.get("id"); let layerFeatures = result[layerName]; layerNextPopulated.add(layerName); if (!layerFeatures) { layerFeatures = { ids: [], features: [], }; result[layerName] = layerFeatures; } if (!layerFeatures.ids.includes(id)) { layerFeatures.ids.push(id); layerFeatures.features.push(f.feature); } }); layerNextPopulated.forEach((l) => layerAlreadyPopulated.add(l)); } return result; }; loadChangedFeaturesFrom = ( layerName: string, layerDef: LolOpenLayersLayerDef | undefined, featureData: IFeatureSource[] | string | GeoImage ) => { const layer = this.findMapLayerByName(layerName); if (!layer) throw new Error(`loadFeaturesFrom unknown ${layerName}`); if (layer.constructor === VectorLayer) { if (featureData) { if (!Array.isArray(featureData)) { throw new Error(`Set feature URL for ${layerName}'s vector data`); } // array of features - can load to vectorsource const source = ( layer as VectorLayer> ).getSource(); if (!source) throw new Error( `LolOpenLayersMap: Vector layer ${layerName} has no source` ); const newFeatures = createMapFeatures( featureData, layerDef?.source?.projection ); if (!this.featuresEqual(source.getFeatures(), newFeatures)) { source.clear(); source.addFeatures(newFeatures); } return; } } if (layer.constructor === TileLayer) { if (featureData) { if (typeof featureData === "string") { // text interpreted as URL for XYZ source log.debug(`set url ${featureData}`); const source = (layer as TileLayer).getSource(); if (source) { source?.setUrl(featureData as string); } else { throw new Error( `LolOpenLayersMap: Vector layer ${layerName} has no source` ); } } else { throw new Error( `Setting feature array for tile data on layer ${layerName} - not supported (to ${JSON.stringify( featureData )}` ); } } } if (layer.constructor === ImageLayer && featureData) { if (typeof featureData !== "object" || Array.isArray(featureData)) { const error = `Setting feature array for image data on layer ${layerName} - not supported expected a GeoImage`; console.error(error, featureData); throw new Error(error); } (layer as ImageLayer).setSource(featureData as GeoImage); } }; /** * Causes a redraw of the layer and any label layer * @param layerName - the *base* layer name */ layerChanged = (layerName: string) => { this.findMapLayerByName(layerName)?.changed(); this.labelLayerChanged(layerName, true); }; labelLayerChanged = ( layerName: string, underlyingLayerDone: boolean = false ) => { const labelLayer = this.findMapLayerByName(layerName + "_labels"); if (labelLayer) { labelLayer.changed(); } else if (!underlyingLayerDone) { const underlyingLayer = this.findMapLayerByName(layerName); underlyingLayer?.changed(); } }; layerNames = () => this.map ?.getLayers() ?.getArray() ?.map((l) => l.getClassName()) ?? []; layerDefs = () => Object.fromEntries( (this.mapProps?.layers ?? []).map((layer: LolOpenLayersLayerDef) => [ layer.name, layer, ]) ); featuresEqual = (featuresA: FeatureLike[], featuresB: FeatureLike[]) => { if (featuresA.length !== featuresB.length) return false; return !featuresA.some( (fA, idx) => fA.getId() !== featuresB[idx].getId() || fA.getProperties() !== featuresB[idx].getProperties() ); }; private findLayerDefByName = (layerName: string) => this.mapProps?.layers?.find((l) => l.name === layerName); private isVisibleAtStart(layerDef: LolOpenLayersLayerDef) { return this.withInitialZoom ? ((layerDef as LolOpenLayersVectorLayerDef).inInitialZoom ?? false) : (layerDef.visible ?? true); } getConfig(): LolOpenLayersMapProps | undefined { return this.mapProps; } getUnclippedFeatures(layerName: string): IFeatureSource[] { if (!this.unclippedFeatures[layerName]) { throw new Error(`getUnclippedFeatures for ${layerName} found nowt`); } return this.unclippedFeatures[layerName]; } getPlacementParams(): PlacementParams | undefined { const mapSizePixels = this.map.getSize(); const mapExtent = this.map.getView().calculateExtent(mapSizePixels); return createPlacementParams( mapSizePixels, mapExtent, this.mapProps?.defaultDataProjection ?? "EPSG:1" ); } } let mapImplementInstance: MapImplement; export const getMapImplement = () => { if (!mapImplementInstance) mapImplementInstance = new MapImplement(); return mapImplementInstance; };