import { InternalContextType } from "../context/LolOpenLayersMapContext"; import { Coordinate } from "ol/coordinate"; import log from "../utils/Log"; import { IMapImplement } from "./MapImplement"; import { IFeatureSource } from "../sourceDefinition/LolOpenLayersSourceDef"; import { compact } from "lodash-es"; import { Extent } from "ol/extent"; import GeoJSON from "ol/format/GeoJSON"; import bboxClip from "@turf/bbox-clip"; import { LolOpenLayersVectorLayerDef } from "../layerDefinition/LolOpenLayersVectorLayerDef"; export const loadAndClipFeatures = ( mapImplement: IMapImplement, internalContext: InternalContextType, bl: Coordinate, tr: Coordinate ) => { log.info(`DEBUG: loadAndClipFeatures: bl=${bl}, tr=${tr}`); ( internalContext.ref()?.enableClipFeatureLayers() ?? new Set() ).forEach((layerName: string) => { const layerDef = mapImplement .getConfig() ?.layers?.find((l) => l.name === layerName); const dataProjection = layerDef?.source?.projection ?? "EPSG:1"; const layerToClip = (layerDef as LolOpenLayersVectorLayerDef).labelStyle ? `${layerName}_labels` : layerName; mapImplement.updateSource( layerToClip, layerDef, clipFeatures( mapImplement.getUnclippedFeatures(layerName), [bl, tr], dataProjection ) ); }); }; const clipFeatures = ( src: IFeatureSource[], box: Coordinate[], dataProjection: string ) => { const boxArray = [box[0][0], box[0][1], box[1][0], box[1][1]]; const boxExtent = boxArray as Extent; return compact( src.map((f) => { const geom = new GeoJSON().readGeometry(f.shape?.geometry, { dataProjection: dataProjection, featureProjection: "EPSG:3857", }); if (geom?.intersectsExtent(boxExtent)) { log.debug(`DEBUG: clipFeatures: ${f.id}:${f.label} in extent`); const geomJson = new GeoJSON().writeGeometryObject(geom, { dataProjection: dataProjection, featureProjection: dataProjection, }); log.debug(`DEBUG: clipFeatures: geomJson=${JSON.stringify(geomJson)}`); // @ts-ignore const clippedGeomJson = bboxClip(geomJson, boxArray); log.debug( `DEBUG: clipFeatures: clippedGeomJson = ${JSON.stringify( clippedGeomJson )}` ); const clippedGeom = new GeoJSON().readGeometry( clippedGeomJson.geometry, { dataProjection: dataProjection, featureProjection: dataProjection, } ); log.debug( `DEBUG: clipFeatures: clippedGeom=${JSON.stringify(clippedGeom)}` ); const clippedFeature = { ...f, shape: { geometry: new GeoJSON().writeGeometryObject(clippedGeom, { dataProjection: dataProjection, featureProjection: "EPSG:3857", }), }, }; log.debug( `DEBUG: clipFeatures: clippedFeature = ${JSON.stringify( clippedFeature )}` ); return clippedFeature; } log.debug( `DEBUG: clipFeatures: ${f.id}:${f.label} ${JSON.stringify( geom )} outside extent` ); return null; }) ); };