Skip to content

Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.

feat(raster-tile-layer): picking info (#3767)

Igor Dykhtaba7c67dbcce5
diff --git a/src/actions/src/vis-state-actions.ts b/src/actions/src/vis-state-actions.ts
index 77a853fc9..bfdd4bba5 100644
--- a/src/actions/src/vis-state-actions.ts
+++ b/src/actions/src/vis-state-actions.ts
@@ -2142,8 +2142,9 @@ export type ExtractDataFromFeatureUpdaterAction = {
/**
* Copy in-memory rows that fall inside the currently selected Draw on Map polygon
* into a new local dataset. Vector tile layers extract a snapshot of features
- * already loaded in the current view. No-ops for raster/WMS/3D/bitmap tiles,
- * unsupported layer types, and non-polygon drawings.
+ * already loaded in the current view. Raster tile layers download a PNG clip and
+ * a GeoJSON file with the export rectangle and zonal stats. No-ops for WMS/3D/bitmap tiles, unsupported layer types,
+ * and non-polygon drawings.
* @memberof visStateActions
* @param layerId Layer whose dataset should be extracted
* @return action
diff --git a/src/components/src/map/layer-hover-info.tsx b/src/components/src/map/layer-hover-info.tsx
index 4d1931f3d..f1b3a7465 100644
--- a/src/components/src/map/layer-hover-info.tsx
+++ b/src/components/src/map/layer-hover-info.tsx
@@ -216,6 +216,51 @@ const EntryInfoRow: React.FC<EntryInfoRowProps> = ({
);
};
+const FeatureInfoRows: React.FC<{
+ rows: Array<{name: string; value: string}>;
+ primaryRows?: Array<{name: string; value: string}> | null;
+ compareType?: CompareType;
+ isComparing: boolean;
+}> = ({rows, primaryRows, compareType, isComparing}) => {
+ const primaryByName = useMemo(() => {
+ const map = new Map<string, string>();
+ (primaryRows || []).forEach(row => {
+ map.set(row.name, row.value);
+ });
+ return map;
+ }, [primaryRows]);
+
+ return (
+ <tbody>
+ {rows.map(({name, value}, i) => {
+ let deltaValue: string | null = null;
+ if (isComparing) {
+ const primaryValue = primaryByName.get(name);
+ const numericValue = Number(value);
+ const numericPrimary = primaryValue === undefined ? NaN : Number(primaryValue);
+ if (Number.isFinite(numericValue) && Number.isFinite(numericPrimary)) {
+ deltaValue = getTooltipDisplayDeltaValue({
+ field: {type: 'real', name} as Field,
+ value: numericValue,
+ primaryValue: numericPrimary,
+ compareType
+ });
+ }
+ }
+ return (
+ <Row
+ key={`${name}-${i}`}
+ name={name}
+ value={value}
+ deltaValue={deltaValue}
+ isComparing={isComparing}
+ />
+ );
+ })}
+ </tbody>
+ );
+};
+
const CellInfo = ({
fieldsToShow,
data,
@@ -347,6 +392,7 @@ const LayerHoverInfoFactory = () => {
const hasFieldsToShow =
(data.fieldValues && Object.keys(data.fieldValues).length > 0) ||
(data.wmsFeatureData && data.wmsFeatureData.length > 0) ||
+ (data.rasterFeatureData && data.rasterFeatureData.length > 0) ||
(props.fieldsToShow && props.fieldsToShow.length > 0);
return (
@@ -357,16 +403,24 @@ const LayerHoverInfoFactory = () => {
</StyledLayerName>
{hasFieldsToShow && <StyledDivider />}
<StyledTable className={props.primaryData ? 'comparing' : undefined}>
- {data.wmsFeatureData ? (
- <tbody>
- {data.wmsFeatureData.map(({name, value}, i) => (
- <Row key={i} name={name} value={value} />
- ))}
- </tbody>
+ {data.wmsFeatureData || data.rasterFeatureData ? (
+ <FeatureInfoRows
+ rows={data.wmsFeatureData || data.rasterFeatureData}
+ primaryRows={
+ props.primaryData?.wmsFeatureData || props.primaryData?.rasterFeatureData
+ }
+ compareType={props.compareType}
+ isComparing={Boolean(props.primaryData)}
+ />
) : data.fieldValues ? (
<tbody>
{data.fieldValues.map(({labelMessage, value}, i) => (
- <Row key={i} name={intl.formatMessage({id: labelMessage})} value={value} />
+ <Row
+ key={i}
+ name={intl.formatMessage({id: labelMessage})}
+ value={value}
+ isComparing={Boolean(props.primaryData)}
+ />
))}
</tbody>
) : props.layer.isAggregated ? (
diff --git a/src/components/src/side-panel/layer-panel/raster-tile-layer-configurator.tsx b/src/components/src/side-panel/layer-panel/raster-tile-layer-configurator.tsx
index ccc90a73a..861c220a4 100644
--- a/src/components/src/side-panel/layer-panel/raster-tile-layer-configurator.tsx
+++ b/src/components/src/side-panel/layer-panel/raster-tile-layer-configurator.tsx
@@ -439,6 +439,12 @@ function RasterTileLayerConfiguratorFactory(
}
}, [onVisConfigChange, preset, singleBandName, singleBandOptions]);
+ const interactionUI = (
+ <LayerConfigGroup {...visConfiguratorProps} label="layer.interaction" collapsible={false}>
+ <VisConfigSwitch {...visConfiguratorProps} {...layer.visConfigSettings.allowHover} />
+ </LayerConfigGroup>
+ );
+
const elevationUI = (
<>
{(stac.rasterServerSupportsElevation ??
@@ -467,6 +473,7 @@ function RasterTileLayerConfiguratorFactory(
<LayerConfigGroup {...visConfiguratorProps} label="Visual Settings" collapsible={false}>
<VisConfigSlider {...layer.visConfigSettings.opacity} {...visConfiguratorProps} />
</LayerConfigGroup>
+ {interactionUI}
{elevationUI}
<LayerConfigGroup {...visConfiguratorProps} label="Debug" collapsible>
<ConfigGroupCollapsibleContent>
@@ -706,6 +713,7 @@ function RasterTileLayerConfiguratorFactory(
)}
{elevationUI}
+ {interactionUI}
<LayerConfigGroup {...visConfiguratorProps} label="Debug" collapsible>
<ConfigGroupCollapsibleContent>
diff --git a/src/layers/src/index.ts b/src/layers/src/index.ts
index 2c4063f7a..1dc76f1e2 100644
--- a/src/layers/src/index.ts
+++ b/src/layers/src/index.ts
@@ -84,8 +84,25 @@ export {
RASTER_COLOR_RESET_PARAMS,
PRESET_OPTIONS
} from './raster-tile/config';
-export {RasterLayerResources} from './raster-tile/url';
export {getCategoricalColormapDataUrl} from './raster-tile/image';
+export {
+ computeDerivedValue,
+ computeRasterZonalStats,
+ findBestTileAtLngLat,
+ formatRasterIdentifyRows,
+ formatRasterValue,
+ latToMercatorY,
+ lngLatToTileUV,
+ lngToMercatorX,
+ mercatorPixelSizeForBbox,
+ parseTitilerPointResponse,
+ rasterZonalStatsToSidecar,
+ sampleRasterTileAtLngLat,
+ tilePixelToLngLat,
+ zonalStatsToProperties
+} from './raster-tile/raster-tile-identify';
+export {RasterLayerResources, getTitilerBboxUrl, getTitilerPointUrl} from './raster-tile/url';
+export {polygonToBboxRectangle, isDownloadableImageBlob} from './raster-tile/raster-tile-extract';
export * from './raster-tile/types';
export * from './raster-tile/raster-tile-utils';
diff --git a/src/layers/src/raster-tile/config.ts b/src/layers/src/raster-tile/config.ts
index 66cc6c0c8..ef0456035 100644
--- a/src/layers/src/raster-tile/config.ts
+++ b/src/layers/src/raster-tile/config.ts
@@ -1,7 +1,6 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-import {RasterTileLayerColorMaps, RasterTileLayerPresets} from './raster-tile-layer-schema';
import {
VisConfigBoolean,
VisConfigNumber,
@@ -10,6 +9,8 @@ import {
VisConfigInput
} from '@kepler.gl/types';
+import {RasterTileLayerColorMaps, RasterTileLayerPresets} from './raster-tile-layer-schema';
+
import {ColorRescaling, ConfigOption, PresetData, BandCombination} from './types';
/**
@@ -738,6 +739,14 @@ export const rasterVisConfigs = {
step: 0.05,
type: 'number'
} as VisConfigNumber,
+ allowHover: {
+ type: 'boolean',
+ defaultValue: false,
+ label: 'layerVisConfigs.allowHover',
+ description: 'layerVisConfigs.allowHoverDescription',
+ group: '',
+ property: 'allowHover'
+ } as VisConfigBoolean,
_stacQuery: {
defaultValue: null,
type: 'input'
diff --git a/src/layers/src/raster-tile/raster-tile-extract.ts b/src/layers/src/raster-tile/raster-tile-extract.ts
new file mode 100644
index 000000000..3797eb200
--- /dev/null
+++ b/src/layers/src/raster-tile/raster-tile-extract.ts
@@ -0,0 +1,301 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import type {Feature, Polygon} from 'geojson';
+import type {TypedArray} from '@loaders.gl/loader-utils';
+
+import {withPublicTitilerCorsCacheKey} from '@kepler.gl/common-utils';
+
+import {
+ RasterIdentifyContext,
+ getTilePixelSize,
+ latToMercatorY,
+ lngToMercatorX,
+ mercatorPixelSizeForBbox
+} from './raster-tile-identify';
+import {getSingleCOGUrlParams, getTitilerBboxUrl} from './url';
+import type {CompleteSTACObject} from './types';
+
+const MAX_EXPORT_SIZE = 2048;
+
+type TileLike = {
+ index?: {x: number; y: number; z: number};
+ bbox?: {west: number; south: number; east: number; north: number};
+ data?: any;
+};
+
+function polygonBbox(polygon: Feature<Polygon>): [number, number, number, number] | null {
+ const rings = polygon.geometry?.coordinates;
+ if (!rings?.[0]?.length) {
+ return null;
+ }
+ let minX = Infinity;
+ let minY = Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+ for (let r = 0; r < rings.length; r++) {
+ const ring = rings[r];
+ for (let i = 0; i < ring.length; i++) {
+ minX = Math.min(minX, ring[i][0]);
+ minY = Math.min(minY, ring[i][1]);
+ maxX = Math.max(maxX, ring[i][0]);
+ maxY = Math.max(maxY, ring[i][1]);
+ }
+ }
+ if (!Number.isFinite(minX)) {
+ return null;
+ }
+ return [minX, minY, maxX, maxY];
+}
+
+/** Axis-aligned lon/lat rectangle covering the polygon. */
+export function polygonToBboxRectangle(polygon: Feature<Polygon>): Feature<Polygon> | null {
+ const bbox = polygonBbox(polygon);
+ if (!bbox) {
+ return null;
+ }
+ const [minLng, minLat, maxLng, maxLat] = bbox;
+ return {
+ type: 'Feature',
+ properties: {...(polygon.properties || {}), shape: 'Rectangle'},
+ geometry: {
+ type: 'Polygon',
+ coordinates: [
+ [
+ [minLng, minLat],
+ [maxLng, minLat],
+ [maxLng, maxLat],
+ [minLng, maxLat],
+ [minLng, minLat]
+ ]
+ ]
+ }
+ };
+}
+
+function scaleBandToByte(value: number, min: number, max: number): number {
+ if (!Number.isFinite(value)) {
+ return 0;
+ }
+ if (max <= min) {
+ return Math.max(0, Math.min(255, Math.round(value)));
+ }
+ return Math.max(0, Math.min(255, Math.round(((value - min) / (max - min)) * 255)));
+}
+
+function getBandMinMax(data: TypedArray): [number, number] {
+ let min = Infinity;
+ let max = -Infinity;
+ for (let i = 0; i < data.length; i++) {
+ const value = data[i];
+ if (!Number.isFinite(value)) {
+ continue;
+ }
+ min = Math.min(min, value);
+ max = Math.max(max, value);
+ }
+ return [min === Infinity ? 0 : min, max === -Infinity ? 1 : max];
+}
+
+function drawTileOntoCanvas(
+ ctx: CanvasRenderingContext2D,
+ tile: TileLike,
+ canvasBounds: {
+ minX: number;
+ minY: number;
+ maxX: number;
+ maxY: number;
+ width: number;
+ height: number;
+ z: number;
+ }
+): void {
+ const index = tile.index;
+ const size = getTilePixelSize(tile);
+ if (!index || !size || index.z !== canvasBounds.z) {
+ return;
+ }
+
+ const n = 2 ** index.z;
+ const tileMinX = index.x / n;
+ const tileMinY = index.y / n;
+ const tileMaxX = (index.x + 1) / n;
+ const tileMaxY = (index.y + 1) / n;
+
+ const dx =
+ ((tileMinX - canvasBounds.minX) / (canvasBounds.maxX - canvasBounds.minX)) * canvasBounds.width;
+ const dy =
+ ((tileMinY - canvasBounds.minY) / (canvasBounds.maxY - canvasBounds.minY)) *
+ canvasBounds.height;
+ const dw = ((tileMaxX - tileMinX) / (canvasBounds.maxX - canvasBounds.minX)) * canvasBounds.width;
+ const dh =
+ ((tileMaxY - tileMinY) / (canvasBounds.maxY - canvasBounds.minY)) * canvasBounds.height;
+
+ const rgbaSource = tile.data?.images?.imageRgba?.data || tile.data?.image;
+ if (rgbaSource && typeof document !== 'undefined') {
+ try {
+ ctx.drawImage(rgbaSource, dx, dy, dw, dh);
+ return;
+ } catch {
+ // Fall through to ImageData path when the source is a raw buffer
+ }
+ }
+
+ const bands = tile.data?.images?.imageBands;
+ if (!Array.isArray(bands) || !bands.length) {
+ return;
+ }
+
+ const imageData = new ImageData(size.width, size.height);
+ const ranges = bands.map(band => (band?.data ? getBandMinMax(band.data) : [0, 1]));
+ const channelCount = Math.min(3, bands.length);
+ for (let i = 0; i < size.width * size.height; i++) {
+ const dest = i * 4;
+ for (let c = 0; c < channelCount; c++) {
+ const value = bands[c]?.data?.[i];
+ imageData.data[dest + c] = scaleBandToByte(value, ranges[c][0], ranges[c][1]);
+ }
+ if (channelCount === 1) {
+ imageData.data[dest + 1] = imageData.data[dest];
+ imageData.data[dest + 2] = imageData.data[dest];
+ }
+ const mask = tile.data?.images?.imageMask?.data?.[i];
+ imageData.data[dest + 3] = mask !== undefined && mask < 1 ? 0 : 255;
+ }
+
+ const tileCanvas = document.createElement('canvas');
+ tileCanvas.width = size.width;
+ tileCanvas.height = size.height;
+ const tileCtx = tileCanvas.getContext('2d');
+ if (!tileCtx) {
+ return;
+ }
+ tileCtx.putImageData(imageData, 0, 0);
+ ctx.drawImage(tileCanvas, dx, dy, dw, dh);
+}
+
+export function isDownloadableImageBlob(blob: Blob | null | undefined): boolean {
+ return Boolean(blob && blob.size > 0 && blob.type.startsWith('image/'));
+}
+
+function canvasToPng(canvas: HTMLCanvasElement): Promise<Blob | null> {
+ return new Promise(resolve => {
+ canvas.toBlob(blob => resolve(blob), 'image/png');
+ });
+}
+
+/**
+ * Composite loaded raster tiles that intersect a polygon into a PNG blob.
+ * Non-rectangular drawings use the lon/lat bounding box as a rectangle.
+ */
+export async function mosaicTilesToPng(
+ tiles: Array<TileLike | null | undefined>,
+ polygon: Feature<Polygon>,
+ _context: RasterIdentifyContext
+): Promise<Blob | null> {
+ if (typeof document === 'undefined') {
+ return null;
+ }
+ const bbox = polygonBbox(polygon);
+ if (!bbox) {
+ return null;
+ }
+
+ const liveTiles = tiles.filter(tile => tile?.data && tile.index) as TileLike[];
+ if (!liveTiles.length) {
+ return null;
+ }
+ const z = Math.max(...liveTiles.map(tile => tile.index?.z ?? 0));
+ const zoomTiles = liveTiles.filter(tile => tile.index?.z === z);
+ const sampleSize = getTilePixelSize(zoomTiles[0]);
+ if (!sampleSize) {
+ return null;
+ }
+
+ const n = 2 ** z;
+ const minX = lngToMercatorX(bbox[0]);
+ const maxX = lngToMercatorX(bbox[2]);
+ const minY = latToMercatorY(bbox[3]);
+ const maxY = latToMercatorY(bbox[1]);
+
+ const worldW = Math.max(maxX - minX, 1e-9);
+ const worldH = Math.max(maxY - minY, 1e-9);
+ let width = Math.round(worldW * sampleSize.width * n);
+ let height = Math.round(worldH * sampleSize.height * n);
+ const scale = Math.min(1, MAX_EXPORT_SIZE / Math.max(width, height, 1));
+ width = Math.max(1, Math.round(width * scale));
+ height = Math.max(1, Math.round(height * scale));
+
+ const canvas = document.createElement('canvas');
+ canvas.width = width;
+ canvas.height = height;
+ const ctx = canvas.getContext('2d');
+ if (!ctx) {
+ return null;
+ }
+
+ const canvasBounds = {minX, minY, maxX, maxY, width, height, z};
+ for (let i = 0; i < zoomTiles.length; i++) {
+ drawTileOntoCanvas(ctx, zoomTiles[i], canvasBounds);
+ }
+
+ return canvasToPng(canvas);
+}
+
+export async function fetchTitilerBboxPng(options: {
+ stac: CompleteSTACObject & {rasterTileServerUrls?: string[]};
+ loadAssetId: string;
+ loadBandIndexes: number[];
+ bbox: [number, number, number, number];
+ width?: number;
+ height?: number;
+}): Promise<Blob | null> {
+ const {stac, loadAssetId, loadBandIndexes, bbox} = options;
+ if (!stac.rasterTileServerUrls?.length || stac.type !== 'Feature') {
+ return null;
+ }
+
+ const params = getSingleCOGUrlParams({
+ stac: stac as any,
+ loadAssetId,
+ loadBandIndexes,
+ mask: false
+ });
+ if (!params) {
+ return null;
+ }
+
+ const size =
+ options.width && options.height
+ ? {width: options.width, height: options.height}
+ : mercatorPixelSizeForBbox(bbox, 2048);
+
+ const urlInfo = getTitilerBboxUrl({
+ stac: stac as any,
+ useSTACSearching: false,
+ bbox,
+ width: size.width,
+ height: size.height,
+ format: 'png'
+ });
+ const url = withPublicTitilerCorsCacheKey(`${urlInfo.url}?${params.toString()}`);
+ const response = await fetch(url);
+ if (!response.ok) {
+ return null;
+ }
+ const blob = await response.blob();
+ return isDownloadableImageBlob(blob) ? blob : null;
+}
+
+export function downloadBlob(blob: Blob, fileName: string): void {
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement('a');
+ link.setAttribute('href', url);
+ link.setAttribute('download', fileName);
+ document.body.appendChild(link);
+ link.dispatchEvent(new MouseEvent('click', {bubbles: false, cancelable: true, view: window}));
+ document.body.removeChild(link);
+ URL.revokeObjectURL(url);
+}
+
+export {polygonBbox};
diff --git a/src/layers/src/raster-tile/raster-tile-identify.ts b/src/layers/src/raster-tile/raster-tile-identify.ts
new file mode 100644
index 000000000..c3c8f8401
--- /dev/null
+++ b/src/layers/src/raster-tile/raster-tile-identify.ts
@@ -0,0 +1,696 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {booleanWithin} from '@turf/boolean-within';
+import {point as turfPoint} from '@turf/helpers';
+import type {Feature, FeatureCollection, Polygon} from 'geojson';
+import type {TypedArray} from '@loaders.gl/loader-utils';
+
+import {BandCombination} from './types';
+import {PRESET_OPTIONS} from './config';
+
+export type RasterIdentifyRow = {name: string; value: string};
+
+export type RasterIdentifyContext = {
+ isPMTiles: boolean;
+ bandCombination: BandCombination | string;
+ preset?: string;
+ loadAssetIds?: string[];
+ loadBandIndexes?: number[];
+ renderBandIndexes?: number[] | null;
+};
+
+export type RasterBandStats = {
+ count: number;
+ min: number;
+ max: number;
+ mean: number;
+ sum: number;
+};
+
+export type RasterZonalStats = {
+ pixelCount: number;
+ bands: Record<string, RasterBandStats>;
+ derived?: RasterBandStats;
+ derivedName?: string;
+};
+
+type TileIndex = {x: number; y: number; z: number};
+
+type TileLike = {
+ index?: TileIndex;
+ bbox?: {west: number; south: number; east: number; north: number};
+ data?: any;
+};
+
+const MAX_ZONAL_PIXELS = 2_000_000;
+
+function derivedLabelFromContext(context: RasterIdentifyContext): string | undefined {
+ return context.preset ? PRESET_OPTIONS[context.preset]?.label : undefined;
+}
+
+/**
+ * Convert lng/lat to fractional pixel coordinates within an XYZ WebMercator tile.
+ * u,v are in [0, 1] when the point is inside the tile.
+ */
+export function lngLatToTileUV(lng: number, lat: number, index: TileIndex): [number, number] {
+ const n = 2 ** index.z;
+ const x = ((lng + 180) / 360) * n;
+ const latRad = (lat * Math.PI) / 180;
+ const y = ((1 - Math.log(Math.tan(latRad) + 1 / Math.cos(latRad)) / Math.PI) / 2) * n;
+ return [x - index.x, y - index.y];
+}
+
+export function tilePixelToLngLat(
+ col: number,
+ row: number,
+ width: number,
+ height: number,
+ index: TileIndex
+): [number, number] {
+ const n = 2 ** index.z;
+ const x = index.x + (col + 0.5) / width;
+ const y = index.y + (row + 0.5) / height;
+ const lng = (x / n) * 360 - 180;
+ const latRad = Math.atan(Math.sinh(Math.PI * (1 - (2 * y) / n)));
+ return [lng, (latRad * 180) / Math.PI];
+}
+
+/** WebMercator x in [0, 1] at zoom 0. */
+export function lngToMercatorX(lng: number): number {
+ return (lng + 180) / 360;
+}
+
+/** WebMercator y in [0, 1] at zoom 0 (0 = north). */
+export function latToMercatorY(lat: number): number {
+ const latRad = (lat * Math.PI) / 180;
+ return (1 - Math.log(Math.tan(latRad) + 1 / Math.cos(latRad)) / Math.PI) / 2;
+}
+
+/**
+ * Pixel size of a WGS84 bbox that matches its WebMercator aspect ratio.
+ * A wide rectangle becomes a wide image instead of a square.
+ */
+export function mercatorPixelSizeForBbox(
+ bbox: [number, number, number, number],
+ maxSize: number
+): {width: number; height: number} {
+ const widthMerc = Math.max(lngToMercatorX(bbox[2]) - lngToMercatorX(bbox[0]), 1e-12);
+ const heightMerc = Math.max(latToMercatorY(bbox[1]) - latToMercatorY(bbox[3]), 1e-12);
+ const aspect = widthMerc / heightMerc;
+ if (aspect >= 1) {
+ return {
+ width: Math.max(1, Math.round(maxSize)),
+ height: Math.max(1, Math.round(maxSize / aspect))
+ };
+ }
+ return {
+ width: Math.max(1, Math.round(maxSize * aspect)),
+ height: Math.max(1, Math.round(maxSize))
+ };
+}
+
+export function formatRasterValue(value: number): string {
+ if (!Number.isFinite(value)) {
+ return 'n/a';
+ }
+ if (Number.isInteger(value)) {
+ return String(value);
+ }
+ const abs = Math.abs(value);
+ if (abs >= 100) {
+ return value.toFixed(2);
+ }
+ if (abs >= 1) {
+ return value.toFixed(4);
+ }
+ return value.toFixed(6);
+}
+
+export function getTilePixelSize(tile: TileLike | null | undefined): {
+ width: number;
+ height: number;
+} | null {
+ if (!tile?.data) {
+ return null;
+ }
+ const bands = tile.data.images?.imageBands;
+ if (Array.isArray(bands) && bands[0] && bands[0].width && bands[0].height) {
+ return {width: bands[0].width, height: bands[0].height};
+ }
+ const rgbaSource = tile.data.images?.imageRgba?.data || tile.data.image;
+ if (rgbaSource && rgbaSource.width && rgbaSource.height) {
+ return {width: rgbaSource.width, height: rgbaSource.height};
+ }
+ return null;
+}
+
+export function findBestTileAtLngLat(
+ tiles: Array<TileLike | null | undefined>,
+ lng: number,
+ lat: number
+): TileLike | null {
+ let best: TileLike | null = null;
+ let bestZoom = -1;
+ for (let i = 0; i < tiles.length; i++) {
+ const tile = tiles[i];
+ const index = tile?.index;
+ if (!tile?.data || !index) {
+ continue;
+ }
+ const [u, v] = lngLatToTileUV(lng, lat, index);
+ if (u < 0 || v < 0 || u >= 1 || v >= 1) {
+ continue;
+ }
+ if (index.z >= bestZoom) {
+ best = tile;
+ bestZoom = index.z;
+ }
+ }
+ return best;
+}
+
+function sampleTypedBand(
+ band: {data?: TypedArray; width?: number; height?: number},
+ col: number,
+ row: number
+): number | null {
+ const data = band?.data;
+ const width = band?.width;
+ const height = band?.height;
+ if (!data || !width || !height || col < 0 || row < 0 || col >= width || row >= height) {
+ return null;
+ }
+ const value = data[row * width + col];
+ return Number.isFinite(value) ? value : null;
+}
+
+function sampleRgbaPixel(
+ image: {data?: ArrayLike<number>; width?: number; height?: number} | null,
+ col: number,
+ row: number
+): [number, number, number, number] | null {
+ if (!image?.data || !image.width || !image.height) {
+ return null;
+ }
+ if (col < 0 || row < 0 || col >= image.width || row >= image.height) {
+ return null;
+ }
+ const idx = (row * image.width + col) * 4;
+ const data = image.data;
+ if (idx + 3 >= data.length) {
+ return null;
+ }
+ return [data[idx], data[idx + 1], data[idx + 2], data[idx + 3]];
+}
+
+function isNodataMask(
+ maskBand: {data?: TypedArray; width?: number; height?: number} | null,
+ col: number,
+ row: number
+): boolean {
+ if (!maskBand) {
+ return false;
+ }
+ const value = sampleTypedBand(maskBand, col, row);
+ return value === null || value < 1;
+}
+
+export function computeDerivedValue(
+ values: number[],
+ bandCombination: BandCombination | string,
+ derivedLabel?: string
+): {name: string; value: number} | null {
+ const r = values[0];
+ const g = values[1];
+ const b = values[2];
+ if (!Number.isFinite(r)) {
+ return null;
+ }
+
+ switch (bandCombination) {
+ case BandCombination.NormalizedDifference:
+ case 'normalizedDifference': {
+ if (!Number.isFinite(g) || r + g === 0) {
+ return null;
+ }
+ return {name: derivedLabel || 'NDVI', value: (r - g) / (r + g)};
+ }
+ case BandCombination.EnhancedVegetationIndex:
+ case 'enhancedVegetationIndex': {
+ if (!Number.isFinite(g) || !Number.isFinite(b)) {
+ return null;
+ }
+ const denominator = r + 6 * g - 7.5 * b + 1;
+ if (denominator === 0) {
+ return null;
+ }
+ return {name: derivedLabel || 'EVI', value: (2.5 * (r - g)) / denominator};
+ }
+ case BandCombination.SoilAdjustedVegetationIndex:
+ case 'soilAdjustedVegetationIndex': {
+ if (!Number.isFinite(g)) {
+ return null;
+ }
+ const denominator = (r + g + 0.5) * 1.5;
+ if (denominator === 0) {
+ return null;
+ }
+ return {name: derivedLabel || 'SAVI', value: (r - g) / denominator};
+ }
+ case BandCombination.ModifiedSoilAdjustedVegetationIndex:
+ case 'modifiedSoilAdjustedVegetationIndex': {
+ if (!Number.isFinite(g)) {
+ return null;
+ }
+ const toSqrt = (2 * r + 1) * (2 * r + 1) - 8 * (r - g);
+ if (toSqrt < 0) {
+ return null;
+ }
+ return {name: derivedLabel || 'MSAVI', value: (2 * r + 1 - Math.sqrt(toSqrt)) / 2};
+ }
+ default:
+ return null;
+ }
+}
+
+export type RasterSample = {
+ lng: number;
+ lat: number;
+ tileIndex: TileIndex;
+ col: number;
+ row: number;
+ bandValues: number[];
+ bandLabels: string[];
+ rgba?: [number, number, number, number];
+ nodata: boolean;
+};
+
+export function sampleRasterTileAtLngLat(
+ tiles: Array<TileLike | null | undefined>,
+ lng: number,
+ lat: number,
+ context: RasterIdentifyContext
+): RasterSample | null {
+ const tile = findBestTileAtLngLat(tiles, lng, lat);
+ const index = tile?.index;
+ const size = getTilePixelSize(tile);
+ if (!tile || !index || !size) {
+ return null;
+ }
+
+ const [u, v] = lngLatToTileUV(lng, lat, index);
+ const col = Math.min(size.width - 1, Math.max(0, Math.floor(u * size.width)));
+ const row = Math.min(size.height - 1, Math.max(0, Math.floor(v * size.height)));
+
+ const images = tile.data.images;
+ const imageBands: Array<{data?: TypedArray; width?: number; height?: number}> | undefined =
+ images?.imageBands;
+ const maskBand = images?.imageMask || null;
+
+ if (Array.isArray(imageBands) && imageBands.length > 0) {
+ const order =
+ Array.isArray(context.renderBandIndexes) && context.renderBandIndexes.length
+ ? context.renderBandIndexes
+ : imageBands.map((_, i) => i);
+ const bandValues: number[] = [];
+ const bandLabels: string[] = [];
+ for (let i = 0; i < order.length; i++) {
+ const bandIndex = order[i];
+ const value = sampleTypedBand(imageBands[bandIndex], col, row);
+ if (value === null) {
+ continue;
+ }
+ bandValues.push(value);
+ bandLabels.push(context.loadAssetIds?.[bandIndex] || `Band ${bandIndex + 1}`);
+ }
+ return {
+ lng,
+ lat,
+ tileIndex: index,
+ col,
+ row,
+ bandValues,
+ bandLabels,
+ nodata: isNodataMask(maskBand, col, row)
+ };
+ }
+
+ const rgbaImage = images?.imageRgba?.data || tile.data.image;
+ const rgba = sampleRgbaPixel(rgbaImage, col, row);
+ if (!rgba) {
+ return null;
+ }
+ return {
+ lng,
+ lat,
+ tileIndex: index,
+ col,
+ row,
+ bandValues: [rgba[0], rgba[1], rgba[2], rgba[3]],
+ bandLabels: ['R', 'G', 'B', 'A'],
+ rgba,
+ nodata: rgba[3] === 0
+ };
+}
+
+export function formatRasterIdentifyRows(
+ sample: RasterSample,
+ context: RasterIdentifyContext
+): RasterIdentifyRow[] {
+ const {z, x, y} = sample.tileIndex;
+ const rows: RasterIdentifyRow[] = [
+ {name: 'Longitude', value: sample.lng.toFixed(6)},
+ {name: 'Latitude', value: sample.lat.toFixed(6)},
+ {name: 'Tile', value: `${z}/${x}/${y}`},
+ {name: 'Pixel', value: `${sample.col}, ${sample.row}`}
+ ];
+
+ if (sample.nodata) {
+ rows.push({name: 'Value', value: 'NoData'});
+ return rows;
+ }
+
+ if (context.isPMTiles && sample.rgba) {
+ const [r, g, b, a] = sample.rgba;
+ rows.push({name: 'RGBA', value: `${r}, ${g}, ${b}, ${a}`});
+ return rows;
+ }
+
+ for (let i = 0; i < sample.bandValues.length; i++) {
+ rows.push({
+ name: sample.bandLabels[i] || `Band ${i + 1}`,
+ value: formatRasterValue(sample.bandValues[i])
+ });
+ }
+
+ const derived = computeDerivedValue(
+ sample.bandValues,
+ context.bandCombination,
+ derivedLabelFromContext(context)
+ );
+ if (derived) {
+ rows.push({name: derived.name, value: formatRasterValue(derived.value)});
+ }
+
+ return rows;
+}
+
+function emptyStats(): RasterBandStats {
+ return {count: 0, min: Infinity, max: -Infinity, mean: 0, sum: 0};
+}
+
+function addStat(stats: RasterBandStats, value: number): void {
+ if (!Number.isFinite(value)) {
+ return;
+ }
+ stats.count += 1;
+ stats.sum += value;
+ stats.min = Math.min(stats.min, value);
+ stats.max = Math.max(stats.max, value);
+}
+
+function finalizeStats(stats: RasterBandStats): RasterBandStats {
+ return {
+ count: stats.count,
+ min: stats.count ? stats.min : NaN,
+ max: stats.count ? stats.max : NaN,
+ sum: stats.sum,
+ mean: stats.count ? stats.sum / stats.count : NaN
+ };
+}
+
+function polygonBbox(polygon: Feature<Polygon>): [number, number, number, number] | null {
+ const coords = polygon.geometry?.coordinates;
+ if (!coords?.[0]?.length) {
+ return null;
+ }
+ let minX = Infinity;
+ let minY = Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+ const ring = coords[0];
+ for (let i = 0; i < ring.length; i++) {
+ const [lng, lat] = ring[i];
+ minX = Math.min(minX, lng);
+ minY = Math.min(minY, lat);
+ maxX = Math.max(maxX, lng);
+ maxY = Math.max(maxY, lat);
+ }
+ return [minX, minY, maxX, maxY];
+}
+
+function tileIntersectsBbox(tile: TileLike, bbox: [number, number, number, number]): boolean {
+ const tb = tile.bbox;
+ if (!tb) {
+ return true;
+ }
+ return !(tb.east < bbox[0] || tb.west > bbox[2] || tb.north < bbox[1] || tb.south > bbox[3]);
+}
+
+function isInsidePolygon(
+ lng: number,
+ lat: number,
+ polygon: Feature<Polygon>,
+ bbox: [number, number, number, number],
+ isRectangle: boolean
+): boolean {
+ if (lng < bbox[0] || lat < bbox[1] || lng > bbox[2] || lat > bbox[3]) {
+ return false;
+ }
+ if (isRectangle) {
+ return true;
+ }
+ try {
+ return booleanWithin(turfPoint([lng, lat]), polygon);
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Aggregate currently loaded tile pixels that fall inside a polygon.
+ * Uses the highest-zoom tile at each location (tiles are scanned independently;
+ * overlapping parent tiles are skipped when a child of higher zoom exists for that pixel
+ * by only using tiles at the maximum zoom present in the intersecting set).
+ */
+export function computeRasterZonalStats(
+ tiles: Array<TileLike | null | undefined>,
+ polygon: Feature<Polygon>,
+ context: RasterIdentifyContext
+): RasterZonalStats {
+ const bbox = polygonBbox(polygon);
+ if (!bbox) {
+ return {pixelCount: 0, bands: {}};
+ }
+
+ const isRectangle = polygon.properties?.shape === 'Rectangle';
+ const liveTiles = tiles.filter((tile): tile is TileLike =>
+ Boolean(tile?.data && tile.index && tileIntersectsBbox(tile, bbox))
+ );
+ if (!liveTiles.length) {
+ return {pixelCount: 0, bands: {}};
+ }
+
+ const maxZoom = Math.max(...liveTiles.map(tile => tile.index?.z ?? 0));
+ const scanTiles = liveTiles.filter(tile => tile.index?.z === maxZoom);
+
+ const bandStats: Record<string, RasterBandStats> = {};
+ const derivedAcc = emptyStats();
+ let derivedName: string | undefined;
+ let pixelCount = 0;
+ let scanned = 0;
+
+ for (let t = 0; t < scanTiles.length; t++) {
+ const tile = scanTiles[t];
+ const index = tile.index as TileIndex;
+ const size = getTilePixelSize(tile);
+ if (!size) {
+ continue;
+ }
+
+ const sampleContext = context;
+ for (let row = 0; row < size.height; row++) {
+ for (let col = 0; col < size.width; col++) {
+ if (scanned >= MAX_ZONAL_PIXELS) {
+ break;
+ }
+ scanned += 1;
+ const [lng, lat] = tilePixelToLngLat(col, row, size.width, size.height, index);
+ if (!isInsidePolygon(lng, lat, polygon, bbox, isRectangle)) {
+ continue;
+ }
+
+ const sample = sampleRasterTilePixel(tile, col, row, sampleContext);
+ if (!sample || sample.nodata) {
+ continue;
+ }
+ pixelCount += 1;
+ for (let i = 0; i < sample.bandValues.length; i++) {
+ const label = sample.bandLabels[i] || `Band ${i + 1}`;
+ if (!bandStats[label]) {
+ bandStats[label] = emptyStats();
+ }
+ addStat(bandStats[label], sample.bandValues[i]);
+ }
+ const derived = computeDerivedValue(
+ sample.bandValues,
+ context.bandCombination,
+ derivedLabelFromContext(context)
+ );
+ if (derived) {
+ derivedName = derived.name;
+ addStat(derivedAcc, derived.value);
+ }
+ }
+ if (scanned >= MAX_ZONAL_PIXELS) {
+ break;
+ }
+ }
+ }
+
+ const bands: Record<string, RasterBandStats> = {};
+ for (const [name, stats] of Object.entries(bandStats)) {
+ bands[name] = finalizeStats(stats);
+ }
+
+ return {
+ pixelCount,
+ bands,
+ ...(derivedAcc.count ? {derived: finalizeStats(derivedAcc), derivedName} : {})
+ };
+}
+
+function sampleRasterTilePixel(
+ tile: TileLike,
+ col: number,
+ row: number,
+ context: RasterIdentifyContext
+): RasterSample | null {
+ const index = tile.index;
+ if (!index) {
+ return null;
+ }
+ const images = tile.data?.images;
+ const imageBands = images?.imageBands;
+ const maskBand = images?.imageMask || null;
+ if (Array.isArray(imageBands) && imageBands.length > 0) {
+ const order =
+ Array.isArray(context.renderBandIndexes) && context.renderBandIndexes.length
+ ? context.renderBandIndexes
+ : imageBands.map((_, i) => i);
+ const bandValues: number[] = [];
+ const bandLabels: string[] = [];
+ for (let i = 0; i < order.length; i++) {
+ const bandIndex = order[i];
+ const value = sampleTypedBand(imageBands[bandIndex], col, row);
+ if (value === null) {
+ continue;
+ }
+ bandValues.push(value);
+ bandLabels.push(context.loadAssetIds?.[bandIndex] || `Band ${bandIndex + 1}`);
+ }
+ return {
+ lng: 0,
+ lat: 0,
+ tileIndex: index,
+ col,
+ row,
+ bandValues,
+ bandLabels,
+ nodata: isNodataMask(maskBand, col, row)
+ };
+ }
+
+ const rgbaImage = images?.imageRgba?.data || tile.data?.image;
+ const rgba = sampleRgbaPixel(rgbaImage, col, row);
+ if (!rgba) {
+ return null;
+ }
+ return {
+ lng: 0,
+ lat: 0,
+ tileIndex: index,
+ col,
+ row,
+ bandValues: [rgba[0], rgba[1], rgba[2], rgba[3]],
+ bandLabels: ['R', 'G', 'B', 'A'],
+ rgba,
+ nodata: rgba[3] === 0
+ };
+}
+
+export function zonalStatsToProperties(
+ stats: RasterZonalStats,
+ extra: Record<string, string | number | undefined> = {}
+): Record<string, string | number> {
+ const properties: Record<string, string | number> = {
+ pixel_count: stats.pixelCount
+ };
+ for (const [key, value] of Object.entries(extra)) {
+ if (value !== undefined) {
+ properties[key] = value;
+ }
+ }
+ for (const [name, band] of Object.entries(stats.bands)) {
+ const slug = name.replace(/\s+/g, '_').toLowerCase();
+ properties[`${slug}_count`] = band.count;
+ properties[`${slug}_min`] = band.min;
+ properties[`${slug}_max`] = band.max;
+ properties[`${slug}_mean`] = band.mean;
+ }
+ if (stats.derived && stats.derivedName) {
+ const slug = stats.derivedName.toLowerCase();
+ properties[`${slug}_min`] = stats.derived.min;
+ properties[`${slug}_max`] = stats.derived.max;
+ properties[`${slug}_mean`] = stats.derived.mean;
+ }
+ return properties;
+}
+
+export function rasterZonalStatsToSidecar(
+ stats: RasterZonalStats,
+ extra: {layer?: string; preset?: string; geometry?: Polygon | null} = {}
+): FeatureCollection<Polygon | null> {
+ const properties = zonalStatsToProperties(stats, {
+ layer: extra.layer,
+ preset: extra.preset,
+ shape: extra.geometry ? 'Rectangle' : undefined
+ });
+ if (stats.derived && stats.derivedName) {
+ properties.derived = stats.derivedName;
+ }
+ return {
+ type: 'FeatureCollection',
+ features: [
+ {
+ type: 'Feature',
+ properties,
+ geometry: extra.geometry ?? null
+ }
+ ]
+ };
+}
+
+export function parseTitilerPointResponse(payload: any): RasterIdentifyRow[] | null {
+ if (!payload || typeof payload !== 'object') {
+ return null;
+ }
+ const values = payload.values || payload.value;
+ if (!Array.isArray(values) || values.length === 0) {
+ return null;
+ }
+ const names: string[] = Array.isArray(payload.band_names)
+ ? payload.band_names
+ : values.map((_, i) => `Band ${i + 1}`);
+ const rows: RasterIdentifyRow[] = [];
+ if (Array.isArray(payload.coordinates) && payload.coordinates.length >= 2) {
+ rows.push({name: 'Longitude', value: Number(payload.coordinates[0]).toFixed(6)});
+ rows.push({name: 'Latitude', value: Number(payload.coordinates[1]).toFixed(6)});
+ }
+ for (let i = 0; i < values.length; i++) {
+ const value = Number(values[i]);
+ rows.push({name: names[i] || `Band ${i + 1}`, value: formatRasterValue(value)});
+ }
+ return rows;
+}
diff --git a/src/layers/src/raster-tile/raster-tile-layer.ts b/src/layers/src/raster-tile/raster-tile-layer.ts
index 1cd747158..77f56eebb 100644
--- a/src/layers/src/raster-tile/raster-tile-layer.ts
+++ b/src/layers/src/raster-tile/raster-tile-layer.ts
@@ -22,12 +22,14 @@ import {
VisConfigBoolean,
VisConfigInput,
VisConfigRange,
- VisConfigNumber
+ VisConfigNumber,
+ BindedLayerCallbacks
} from '@kepler.gl/types';
-import {notNullorUndefined} from '@kepler.gl/common-utils';
+import {notNullorUndefined, withPublicTitilerCorsCacheKey} from '@kepler.gl/common-utils';
import {Datasets, KeplerTable as KeplerDataset, VectorTileMetadata} from '@kepler.gl/table';
import {getApplicationConfig} from '@kepler.gl/utils';
+import type {Feature, Polygon} from 'geojson';
import {
rasterVisConfigs,
@@ -38,6 +40,24 @@ import {
import {getModules} from './gpu-utils';
import {getSTACImageRequests, loadImages, loadTerrain} from './image';
import RasterIcon from './raster-tile-icon';
+import {
+ computeRasterZonalStats,
+ formatRasterIdentifyRows,
+ parseTitilerPointResponse,
+ sampleRasterTileAtLngLat,
+ zonalStatsToProperties,
+ rasterZonalStatsToSidecar,
+ type RasterIdentifyContext,
+ type RasterIdentifyRow
+} from './raster-tile-identify';
+import {
+ downloadBlob,
+ fetchTitilerBboxPng,
+ mosaicTilesToPng,
+ polygonBbox,
+ polygonToBboxRectangle
+} from './raster-tile-extract';
+import {getSingleCOGUrlParams, getTitilerPointUrl} from './url';
import {
getDataSourceParams,
getDataType,
@@ -62,6 +82,7 @@ import {
KeplerRasterDataset,
Tile2DHeader,
PresetOption,
+ ExtendedKeplerSTAC,
CompleteSTACObject
} from './types';
@@ -124,6 +145,7 @@ const getShouldLoadTerrain = (stac, mapState, visConfig) => {
export type RasterTileLayerVisConfigCommonSettings = {
opacity: VisConfigNumber;
+ allowHover: VisConfigBoolean;
enableTerrain: VisConfigBoolean;
enableTerrainTopView: VisConfigBoolean;
showTileBorders: VisConfigBoolean;
@@ -173,6 +195,16 @@ export default class RasterTileLayer extends KeplerLayer {
_lastRenderedPreset: string | undefined;
/** Timeout ID for deferred redraws */
_redrawTimeout: ReturnType<typeof setTimeout> | undefined;
+ /** Viewport tiles currently held by deck.gl, used for identify / extract */
+ _loadedTiles: any[] = [];
+ /** Band/preset context for sampling currently loaded tiles */
+ _identifyContext: RasterIdentifyContext = {
+ isPMTiles: false,
+ bandCombination: 'rgb'
+ };
+ /** STAC object used by the last render, for Titiler identify / crop */
+ _stac: (CompleteSTACObject & ExtendedKeplerSTAC) | null = null;
+ _useSTACSearching = false;
getDataSourceParams: (
stac: CompleteSTACObject,
@@ -267,10 +299,243 @@ export default class RasterTileLayer extends KeplerLayer {
};
}
- getHoverData() {
+ getHoverData(
+ object,
+ _dataContainer,
+ _fields,
+ _animationConfig,
+ hoverInfo?: {index?: number; coordinate?: number[]}
+ ) {
+ if (!this.config.visConfig.allowHover) {
+ return null;
+ }
+ if (object?.wmsFeatureInfo) {
+ if (Array.isArray(object.wmsFeatureInfo)) {
+ return {rasterFeatureData: object.wmsFeatureInfo};
+ }
+ return {
+ rasterFeatureData: [{name: 'Raster', value: String(object.wmsFeatureInfo)}]
+ };
+ }
+
+ const coordinate = hoverInfo?.coordinate || object?.coordinate;
+ if (!Array.isArray(coordinate) || coordinate.length < 2) {
+ return null;
+ }
+
+ const sample = sampleRasterTileAtLngLat(
+ this._loadedTiles,
+ coordinate[0],
+ coordinate[1],
+ this._identifyContext
+ );
+ if (!sample) {
+ return {
+ rasterFeatureData: [
+ {name: 'Longitude', value: Number(coordinate[0]).toFixed(6)},
+ {name: 'Latitude', value: Number(coordinate[1]).toFixed(6)},
+ {name: 'Value', value: 'No raster tile loaded'}
+ ]
+ };
+ }
+
+ return {rasterFeatureData: formatRasterIdentifyRows(sample, this._identifyContext)};
+ }
+
+ isLayerHovered(objectInfo): boolean {
+ if (!this.config.visConfig.allowHover) {
+ return false;
+ }
+ if (!objectInfo?.picked || !objectInfo?.layer) {
+ return false;
+ }
+ const id = objectInfo.layer.props?.id;
+ if (id === this.id) {
+ return true;
+ }
+ return (
+ typeof id === 'string' &&
+ (id.includes(`raster-2d-layer-${this.id}`) || id.includes(`raster-3d-layer-${this.id}`))
+ );
+ }
+
+ hasHoveredObject(objectInfo: any) {
+ if (this.isLayerHovered(objectInfo)) {
+ return {
+ index: 0,
+ ...objectInfo
+ };
+ }
return null;
}
+ private isPickable(opts): boolean {
+ return Boolean(opts.interactionConfig?.tooltip?.enabled && this.config.visConfig.allowHover);
+ }
+
+ /**
+ * Copy zonal stats for pixels currently loaded under a drawn polygon.
+ * Also used by Extract data in the editor.
+ */
+ extractInsideFeature(feature: Feature<Polygon> | null): {
+ kind: 'geojson';
+ features: Array<{type: 'Feature'; geometry: any; properties: Record<string, string | number>}>;
+ rowCount: number;
+ } | null {
+ if (!feature?.geometry) {
+ return null;
+ }
+ const exportFeature = polygonToBboxRectangle(feature) || feature;
+ const stats = computeRasterZonalStats(this._loadedTiles, exportFeature, this._identifyContext);
+ if (!stats.pixelCount) {
+ return {kind: 'geojson', features: [], rowCount: 0};
+ }
+ const properties = zonalStatsToProperties(stats, {
+ layer: this.config.label,
+ preset: this._identifyContext.preset
+ });
+ return {
+ kind: 'geojson',
+ features: [
+ {
+ type: 'Feature',
+ geometry: exportFeature.geometry,
+ properties
+ }
+ ],
+ rowCount: 1
+ };
+ }
+
+ /**
+ * Download a PNG clip of currently loaded tiles under the polygon, plus a GeoJSON
+ * sidecar with the lon/lat bbox rectangle and zonal stats. Tries Titiler bbox crop
+ * first for single-asset COGs, then a client mosaic.
+ */
+ async downloadClip(feature: Feature<Polygon> | null): Promise<{png: boolean; json: boolean}> {
+ if (!feature?.geometry) {
+ return {png: false, json: false};
+ }
+ const exportFeature = polygonToBboxRectangle(feature) || feature;
+ const stats = computeRasterZonalStats(this._loadedTiles, exportFeature, this._identifyContext);
+ const fileBase = (this.config.label || 'raster').replace(/[^\w.-]+/g, '_');
+ let json = false;
+ let png = false;
+ if (stats.pixelCount) {
+ const sidecar = rasterZonalStatsToSidecar(stats, {
+ layer: this.config.label,
+ preset: this._identifyContext.preset,
+ geometry: exportFeature.geometry
+ });
+ downloadBlob(
+ new Blob([JSON.stringify(sidecar, null, 2)], {type: 'application/json'}),
+ `${fileBase}-clip.json`
+ );
+ json = true;
+ }
+ const bbox = polygonBbox(exportFeature);
+
+ if (
+ this._stac &&
+ !this._identifyContext.isPMTiles &&
+ bbox &&
+ this._identifyContext.loadAssetIds?.length === 1
+ ) {
+ try {
+ const blob = await fetchTitilerBboxPng({
+ stac: this._stac,
+ loadAssetId: this._identifyContext.loadAssetIds[0],
+ loadBandIndexes: this._identifyContext.loadBandIndexes?.length
+ ? this._identifyContext.loadBandIndexes
+ : [0],
+ bbox
+ });
+ if (blob) {
+ downloadBlob(blob, `${fileBase}-clip.png`);
+ return {png: true, json};
+ }
+ } catch {
+ // Fall back to the in-memory mosaic
+ }
+ }
+
+ try {
+ const mosaic = await mosaicTilesToPng(
+ this._loadedTiles,
+ exportFeature,
+ this._identifyContext
+ );
+ if (mosaic) {
+ downloadBlob(mosaic, `${fileBase}-clip.png`);
+ png = true;
+ }
+ } catch {
+ // Report a missing PNG to the caller
+ }
+ return {png, json};
+ }
+
+ private async _onClickIdentify(
+ layerCallbacks: BindedLayerCallbacks | undefined,
+ info: {coordinate?: number[]}
+ ): Promise<void> {
+ const coordinate = info?.coordinate;
+ if (!Array.isArray(coordinate) || coordinate.length < 2) {
+ return;
+ }
+ const rows: RasterIdentifyRow[] | null = await this._fetchTitilerPoint(
+ coordinate[0],
+ coordinate[1]
+ );
+ if (rows && rows.length > 0 && layerCallbacks?.onWMSFeatureInfo) {
+ layerCallbacks.onWMSFeatureInfo({
+ featureInfo: rows,
+ coordinate: [coordinate[0], coordinate[1]]
+ });
+ }
+ }
+
+ private async _fetchTitilerPoint(lon: number, lat: number): Promise<RasterIdentifyRow[] | null> {
+ const stac = this._stac;
+ const assetId = this._identifyContext.loadAssetIds?.[0];
+ if (
+ !stac?.rasterTileServerUrls?.length ||
+ !assetId ||
+ stac.type !== 'Feature' ||
+ (this._identifyContext.loadAssetIds?.length ?? 0) !== 1
+ ) {
+ return null;
+ }
+ try {
+ const params = getSingleCOGUrlParams({
+ stac: stac as any,
+ loadAssetId: assetId,
+ loadBandIndexes: this._identifyContext.loadBandIndexes?.length
+ ? this._identifyContext.loadBandIndexes
+ : [0],
+ mask: false
+ });
+ if (!params) {
+ return null;
+ }
+ const urlInfo = getTitilerPointUrl({
+ stac: stac as any,
+ useSTACSearching: this._useSTACSearching,
+ lon,
+ lat
+ });
+ const response = await fetch(
+ withPublicTitilerCorsCacheKey(`${urlInfo.url}?${params.toString()}`)
+ );
+ if (!response.ok) {
+ return null;
+ }
+ return parseTitilerPointResponse(await response.json());
+ } catch {
+ return null;
+ }
+ }
+
// We can render without columns, so we redefine this method
shouldRenderLayer(): boolean {
return Boolean(this.type && this.config.isVisible);
@@ -410,6 +675,7 @@ export default class RasterTileLayer extends KeplerLayer {
* @param tiles Array of tiles in current viewport
*/
onViewportLoad(tiles: (Tile2DHeader | null)[]): void {
+ this._loadedTiles = tiles.filter(Boolean);
this.updateMinMaxPixelValue(tiles);
const newZRange = computeZRange(tiles);
if (!newZRange) {
@@ -491,7 +757,9 @@ export default class RasterTileLayer extends KeplerLayer {
}
const {visConfig} = this.config;
- const {id, opacity, visible} = this.getDefaultDeckLayerProps(opts);
+ const defaultLayerProps = this.getDefaultDeckLayerProps(opts);
+ const {id, opacity, visible, idx} = defaultLayerProps;
+ const pickable = this.isPickable(opts);
const hasShadowEffect = experimentalContext?.hasShadowEffect;
@@ -586,14 +854,32 @@ export default class RasterTileLayer extends KeplerLayer {
maxCategoricalBandValue
};
+ this._stac = stac;
+ this._useSTACSearching = Boolean(useSTACSearching);
+ this._identifyContext = {
+ isPMTiles: false,
+ bandCombination,
+ preset,
+ loadAssetIds,
+ loadBandIndexes,
+ renderBandIndexes
+ };
+
const tileLayer = new TileLayer<any, RenderSubLayersProps>({
id,
+ idx,
+ pickable,
minZoom,
maxZoom,
tileSize: 512 / devicePixelRatio,
zoomOffset: visConfig.zoomOffset || 0,
getTileData: (args: any) => this.getTileData({...args, ...getTileDataCustomProps}),
onViewportLoad: this.onViewportLoad.bind(this),
+ onClick: pickable
+ ? info => {
+ void this._onClickIdentify(layerCallbacks, info);
+ }
+ : undefined,
// @ts-expect-error - TS doesn't know we'll pass appropriate props here
renderSubLayers: renderSubLayersStac,
maxRequests: getMaxRequests(stac.rasterTileServerUrls || []),
@@ -653,7 +939,9 @@ export default class RasterTileLayer extends KeplerLayer {
}
private renderPMTilesLayer(opts): TileLayer<any>[] {
- const {id, opacity, visible} = this.getDefaultDeckLayerProps(opts);
+ const defaultLayerProps = this.getDefaultDeckLayerProps(opts);
+ const {id, opacity, visible, idx} = defaultLayerProps;
+ const pickable = this.isPickable(opts);
const {data, mapState, layerCallbacks} = opts;
const metadata = data?.dataset?.metadata as VectorTileMetadata;
@@ -667,16 +955,24 @@ export default class RasterTileLayer extends KeplerLayer {
const shouldLoadTerrain = getShouldLoadTerrain(metadata, mapState, visConfig);
+ this._stac = null;
+ this._identifyContext = {
+ isPMTiles: true,
+ bandCombination: 'rgb',
+ preset: 'pmtiles'
+ };
+
return [
new TileLayer<any, RasterTileLayerVisConfigCommonSettings>({
id,
+ idx,
getTileData: (args: any) =>
this.getTileDataPMTiles({...args, shouldLoadTerrain, metadata}, tileSource),
// Assume the pmtiles file support HTTP/2, so we aren't limited by the browser to a certain number per domain.
maxRequests: 20,
- pickable: true,
+ pickable,
autoHighlight: showTileBorders,
onViewportLoad: this.onViewportLoad.bind(this),
diff --git a/src/layers/src/raster-tile/raster-tile-utils.ts b/src/layers/src/raster-tile/raster-tile-utils.ts
index ee59d799c..b6bb4777d 100644
--- a/src/layers/src/raster-tile/raster-tile-utils.ts
+++ b/src/layers/src/raster-tile/raster-tile-utils.ts
@@ -695,7 +695,7 @@ function hasCoreBandsWithDataType(assetData: Record<string, unknown>): boolean {
* @param stac STAC object
* @return Number of permissible concurrent requests
*/
-export function getMaxRequests(rasterTileServerUrls: []): number {
+export function getMaxRequests(rasterTileServerUrls: string[]): number {
return (rasterTileServerUrls.length || 1) * 6;
}
diff --git a/src/layers/src/raster-tile/types.ts b/src/layers/src/raster-tile/types.ts
index a231a265f..e7dbf56cd 100644
--- a/src/layers/src/raster-tile/types.ts
+++ b/src/layers/src/raster-tile/types.ts
@@ -107,7 +107,7 @@ export type CategoricalColormapOptions = {
};
export type ExtendedKeplerSTAC = {
- rasterTileServerUrls?: [];
+ rasterTileServerUrls?: string[];
/** Optional per-layer override for max retries when fetching raster data */
rasterServerMaxRetries?: number;
/** Optional per-layer override for retry delay between attempts (ms) */
diff --git a/src/layers/src/raster-tile/url.ts b/src/layers/src/raster-tile/url.ts
index 7ae8202b8..16ec862de 100644
--- a/src/layers/src/raster-tile/url.ts
+++ b/src/layers/src/raster-tile/url.ts
@@ -190,6 +190,51 @@ export function getTitilerPathMapping(
return 'cog';
}
+/**
+ * Titiler /point endpoint for a lon/lat sample of the COG or mosaic.
+ */
+export function getTitilerPointUrl(options: {
+ stac: GetTileDataProps['stac'];
+ useSTACSearching: boolean;
+ lon: number;
+ lat: number;
+}): {url: string; rasterServerUrl: string} {
+ const {stac, useSTACSearching, lon, lat} = options;
+ if (!stac.rasterTileServerUrls?.length) {
+ throw new Error('No raster tile servers');
+ }
+ const pathStem = getTitilerPathMapping(stac, useSTACSearching);
+ const domain = chooseDomain(stac.rasterTileServerUrls, 0, 0);
+ return {
+ url: `${domain}/${pathStem}/point/${lon},${lat}`,
+ rasterServerUrl: domain
+ };
+}
+
+/**
+ * Titiler /bbox crop of a COG or mosaic as an image.
+ */
+export function getTitilerBboxUrl(options: {
+ stac: GetTileDataProps['stac'];
+ useSTACSearching: boolean;
+ bbox: [number, number, number, number];
+ width: number;
+ height: number;
+ format?: string;
+}): {url: string; rasterServerUrl: string} {
+ const {stac, useSTACSearching, bbox, width, height, format = 'png'} = options;
+ if (!stac.rasterTileServerUrls?.length) {
+ throw new Error('No raster tile servers');
+ }
+ const pathStem = getTitilerPathMapping(stac, useSTACSearching);
+ const domain = chooseDomain(stac.rasterTileServerUrls, 0, 0);
+ const [minx, miny, maxx, maxy] = bbox;
+ return {
+ url: `${domain}/${pathStem}/bbox/${minx},${miny},${maxx},${maxy}/${width}x${height}.${format}`,
+ rasterServerUrl: domain
+ };
+}
+
/**
* Choose from available domains to load images from
*
diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.ts
index c0fb7b0ec..824a3bbc8 100644
--- a/src/reducers/src/vis-state-updaters.ts
+++ b/src/reducers/src/vis-state-updaters.ts
@@ -68,8 +68,10 @@ import {
computeSplitMapLayers,
adjustValueToFilterDomain,
errorNotification,
+ successNotification,
editorFeaturesToFeatureCollection,
extractRowsInsideFeature,
+ isRasterTileExtractLayer,
isVectorTileExtractLayer,
mergeUserFeatureProperties,
toSketchFeature,
@@ -5510,7 +5512,8 @@ export function convertEditorFeaturesToLayerUpdater(
/**
* Copy in-memory rows (or loaded vector-tile features) inside the selected
- * Draw on Map polygon into a new dataset.
+ * Draw on Map polygon into a new dataset. Raster tiles download a PNG clip and a
+ * GeoJSON sidecar (bbox rectangle + stats) instead of creating a dataset.
*/
export function extractDataFromFeatureUpdater(
state: VisState,
@@ -5525,9 +5528,11 @@ export function extractDataFromFeatureUpdater(
return state;
}
+ const isTiledExtract = isVectorTileExtractLayer(layer) || isRasterTileExtractLayer(layer);
+
// GPU range/time filters are not reflected in filteredIndex; evaluate them on CPU
// the same way export data does, then clip the result to the drawing.
- if (!isVectorTileExtractLayer(layer)) {
+ if (!isTiledExtract) {
state = filterDatasetCPU(state, dataId);
dataset = state.datasets[dataId];
if (!dataset) {
@@ -5563,7 +5568,9 @@ export function extractDataFromFeatureUpdater(
ACTION_TASK_ADD_NOTIFICATION().map(() =>
addNotification(
errorNotification({
- message: isVectorTileExtractLayer(layer)
+ message: isRasterTileExtractLayer(layer)
+ ? 'No loaded raster pixels found inside the selected drawing'
+ : isVectorTileExtractLayer(layer)
? 'No loaded vector tile features found inside the selected drawing'
: 'No rows found inside the selected drawing',
id: 'extract-data-from-feature-empty'
@@ -5573,6 +5580,40 @@ export function extractDataFromFeatureUpdater(
);
}
+ if (isRasterTileExtractLayer(layer)) {
+ const polygon = feature;
+ const download =
+ typeof (layer as any).downloadClip === 'function'
+ ? Promise.resolve((layer as any).downloadClip(polygon))
+ : Promise.resolve({png: false, json: false});
+ return withTask(
+ state,
+ UNWRAP_TASK(download).bimap(
+ (result: {png?: boolean} | null) =>
+ addNotification(
+ result?.png
+ ? successNotification({
+ message: 'Downloaded raster clip image and stats file',
+ id: 'extract-raster-clip'
+ })
+ : errorNotification({
+ message: 'Failed to download raster clip image',
+ id: 'extract-raster-clip'
+ })
+ ),
+ err =>
+ addNotification(
+ errorNotification({
+ message: `Failed to download raster clip: ${
+ err instanceof Error ? err.message : String(err)
+ }`,
+ id: 'extract-raster-clip'
+ })
+ )
+ )
+ );
+ }
+
let data;
try {
data =
diff --git a/src/types/layers.d.ts b/src/types/layers.d.ts
index b2d5f30c6..d06ba33ba 100644
--- a/src/types/layers.d.ts
+++ b/src/types/layers.d.ts
@@ -474,10 +474,10 @@ export type BindedLayerCallbacks = {
onLayerHover?: (value: any) => void;
onSetLayerDomain?: (value: any) => void;
onFilteredItemsChange?: (event: {id: string; count: number}) => void;
- onWMSFeatureInfo?: (
- featureInfo: Array<{name: string; value: string}> | string | null,
- coordinate?: [number, number]
- ) => void;
+ onWMSFeatureInfo?: (props: {
+ featureInfo: Array<{name: string; value: string}> | string | null;
+ coordinate?: [number, number] | null;
+ }) => void;
onRedrawNeeded?: () => void;
onFitBounds?: (bounds: [number, number, number, number]) => void;
onTilesetLoadError?: (kind: 'token' | 'generic' | null) => void;
diff --git a/src/utils/src/extract-dataset-utils.ts b/src/utils/src/extract-dataset-utils.ts
index 38a094a73..1c1f96e68 100644
--- a/src/utils/src/extract-dataset-utils.ts
+++ b/src/utils/src/extract-dataset-utils.ts
@@ -107,11 +107,15 @@ export function isVectorTileExtractLayer(layer?: ExtractableLayer | null): boole
return Boolean(layer && layer.type === LAYER_TYPES.vectorTile);
}
+export function isRasterTileExtractLayer(layer?: ExtractableLayer | null): boolean {
+ return Boolean(layer && layer.type === LAYER_TYPES.rasterTile);
+}
+
export function isExtractableLayer(
layer: ExtractableLayer,
datasets: Record<string, ExtractableDataset | undefined>
): boolean {
- if (isVectorTileExtractLayer(layer)) {
+ if (isVectorTileExtractLayer(layer) || isRasterTileExtractLayer(layer)) {
return Boolean(layer.config?.dataId);
}
// getPolygonFilterFunctor returns true for unsupported types, which would copy
@@ -230,11 +234,28 @@ export function extractVectorTileFeaturesInsideFeature({
return {kind: 'geojson', features, rowCount: features.length};
}
+export function extractRasterInsideFeature({
+ layer,
+ feature
+}: {
+ layer: ExtractableLayer;
+ feature: Feature | null;
+}): ExtractedGeojson | null {
+ if (!feature || !canApplyFeatureFilter(feature) || !isRasterTileExtractLayer(layer)) {
+ return null;
+ }
+ if (typeof layer.extractInsideFeature === 'function') {
+ return layer.extractInsideFeature(feature);
+ }
+ return null;
+}
+
/**
* Copy in-memory rows whose geometry falls inside a drawn polygon.
* Existing table filters (range/select/time), including GPU-backed ones via
* `filteredIdxCPU`, are applied; the polygon clip is extra.
* Vector tiles use currently loaded viewport tiles instead of dataset.rows.
+ * Raster tiles report whether any loaded pixels fall inside the drawing.
*/
export function extractRowsInsideFeature({
layer,
@@ -248,6 +269,9 @@ export function extractRowsInsideFeature({
if (isVectorTileExtractLayer(layer)) {
return extractVectorTileFeaturesInsideFeature({layer, feature});
}
+ if (isRasterTileExtractLayer(layer)) {
+ return extractRasterInsideFeature({layer, feature});
+ }
if (
!feature ||
diff --git a/src/utils/src/index.ts b/src/utils/src/index.ts
index 5084fc0e7..a611fdc4b 100644
--- a/src/utils/src/index.ts
+++ b/src/utils/src/index.ts
@@ -170,8 +170,10 @@ export type {EditorFeatureCollection} from './editor-feature-utils';
export {
extractRowsInsideFeature,
extractVectorTileFeaturesInsideFeature,
+ extractRasterInsideFeature,
isExtractableDataset,
isExtractableLayer,
+ isRasterTileExtractLayer,
isVectorTileExtractLayer
} from './extract-dataset-utils';
export type {
diff --git a/test/browser/components/map/map-popover-test.js b/test/browser/components/map/map-popover-test.js
index e2de65b7a..ee6b22b2b 100644
--- a/test/browser/components/map/map-popover-test.js
+++ b/test/browser/components/map/map-popover-test.js
@@ -214,3 +214,55 @@ test('Map Popover - render comparison mode with delta column', t => {
t.end();
});
+
+test('Map Popover - raster tooltip keeps a delta column in comparison mode', t => {
+ const rasterHoverProp = {
+ data: {
+ rasterFeatureData: [
+ {name: 'Longitude', value: '33.738085'},
+ {name: 'Latitude', value: '16.720055'},
+ {name: 'Tile', value: '12/2431/1855'},
+ {name: 'b1', value: '255'},
+ {name: 'b2', value: '178'}
+ ]
+ },
+ layer: {config: {label: 'Africa Farms'}, isAggregated: false},
+ fields: [],
+ fieldsToShow: [],
+ primaryData: {
+ rasterFeatureData: [
+ {name: 'Longitude', value: '33.683164'},
+ {name: 'Latitude', value: '16.714997'},
+ {name: 'b1', value: '131'},
+ {name: 'b2', value: '113'}
+ ]
+ },
+ compareType: COMPARE_TYPES.ABSOLUTE
+ };
+
+ let wrapper;
+ t.doesNotThrow(() => {
+ wrapper = mountWithTheme(
+ <IntlWrapper>
+ <MapPopover {...defaultProps} layerHoverProp={rasterHoverProp} />
+ </IntlWrapper>
+ );
+ }, 'Should render raster tooltip in comparison mode');
+
+ const table = wrapper.find('table').at(0);
+ t.ok(table.hasClass('comparing'), 'Table should use the comparing grid');
+
+ const rows = table.find('.layer-hover-info__row');
+ t.equal(rows.length, 5, 'Should render all raster identify rows');
+ for (let i = 0; i < rows.length; i++) {
+ t.equal(
+ rows.at(i).find('td').length,
+ 3,
+ `Row ${i} should have name, value, and delta cells so the grid does not wrap`
+ );
+ }
+ t.equal(rows.at(0).find('.row__name').text(), 'Longitude');
+ t.equal(rows.at(1).find('.row__name').text(), 'Latitude');
+ t.equal(rows.at(3).find('.row__name').text(), 'b1');
+ t.end();
+});
diff --git a/test/browser/layer-tests/raster-tile-layer-specs.js b/test/browser/layer-tests/raster-tile-layer-specs.js
index 20ae981b9..fc014f831 100644
--- a/test/browser/layer-tests/raster-tile-layer-specs.js
+++ b/test/browser/layer-tests/raster-tile-layer-specs.js
@@ -9,7 +9,16 @@ import {
getUsableAssets,
getRasterStatisticsMinMax,
filterAvailablePresets,
- getDataSourceParams
+ getDataSourceParams,
+ computeDerivedValue,
+ formatRasterIdentifyRows,
+ lngLatToTileUV,
+ mercatorPixelSizeForBbox,
+ parseTitilerPointResponse,
+ polygonToBboxRectangle,
+ isDownloadableImageBlob,
+ rasterZonalStatsToSidecar,
+ sampleRasterTileAtLngLat
} from '@kepler.gl/layers';
import {RasterWebGL} from '@kepler.gl/deckgl-layers';
import {parseRasterMetadata} from '@kepler.gl/table';
@@ -135,6 +144,11 @@ test('#RasterTileLayer -> constructor and basic properties', t => {
t.equal(layer.config.label, 'test raster layer', 'label should be correct');
t.equal(layer.config.isVisible, true, 'should be visible');
t.equal(layer.config.visConfig.opacity, 1, 'should have default opacity');
+ t.equal(
+ layer.config.visConfig.allowHover,
+ false,
+ 'should disable hover tooltips by default'
+ );
t.equal(
layer.config.visConfig.enableTerrain,
true,
@@ -202,11 +216,13 @@ test('#RasterTileLayer -> configuration and visual settings', t => {
layer.updateLayerVisConfig({
opacity: 0.7,
enableTerrain: false,
- enableTerrainTopView: true
+ enableTerrainTopView: true,
+ allowHover: true
});
t.equal(layer.config.visConfig.opacity, 0.7, 'should update opacity');
t.equal(layer.config.visConfig.enableTerrain, false, 'should update terrain');
t.equal(layer.config.visConfig.enableTerrainTopView, true, 'should update terrain top view');
+ t.equal(layer.config.visConfig.allowHover, true, 'should update allowHover');
// Test shouldRenderLayer
t.notOk(layer.shouldRenderLayer(), 'should not render when not visible');
@@ -865,3 +881,287 @@ test('#RasterTileLayer -> float mask keeps the pixels a float32 mask marks as va
);
t.end();
});
+
+test('#RasterTileLayer -> identify samples band values at lng/lat', t => {
+ const [u, v] = lngLatToTileUV(0, 0, {x: 0, y: 0, z: 0});
+ t.ok(Math.abs(u - 0.5) < 1e-6, 'lng 0 is the center of tile 0/0/0 in x');
+ t.ok(Math.abs(v - 0.5) < 1e-6, 'lat 0 is the center of tile 0/0/0 in y');
+
+ const data = new Float32Array([1, 2, 3, 4]);
+ const tile = {
+ index: {x: 0, y: 0, z: 0},
+ bbox: {west: -180, south: -85, east: 180, north: 85},
+ data: {
+ images: {
+ imageBands: [{data, width: 2, height: 2}]
+ }
+ }
+ };
+
+ const sample = sampleRasterTileAtLngLat([tile], 0, 0, {
+ isPMTiles: false,
+ bandCombination: 'single',
+ loadAssetIds: ['ndvi']
+ });
+ t.ok(sample, 'should sample a loaded tile');
+ t.equal(sample.col, 1, 'center of a 2x2 tile is column 1');
+ t.equal(sample.row, 1, 'center of a 2x2 tile is row 1');
+ t.equal(sample.bandValues[0], 4, 'should read the bottom-right pixel');
+
+ const rows = formatRasterIdentifyRows(sample, {
+ isPMTiles: false,
+ bandCombination: 'single',
+ loadAssetIds: ['ndvi']
+ });
+ t.ok(
+ rows.some(row => row.name === 'ndvi' && row.value === '4'),
+ 'tooltip rows include the band value'
+ );
+
+ const ndvi = computeDerivedValue([0.8, 0.2], 'normalizedDifference');
+ t.ok(ndvi, 'should compute NDVI');
+ t.equal(ndvi.name, 'NDVI');
+ t.ok(Math.abs(ndvi.value - 0.6) < 1e-6, 'NDVI (0.8-0.2)/(0.8+0.2) = 0.6');
+
+ const ndmi = computeDerivedValue([0.8, 0.2], 'normalizedDifference', 'NDMI');
+ t.equal(ndmi.name, 'NDMI', 'normalized-difference presets should use the active index label');
+
+ const parsed = parseTitilerPointResponse({
+ coordinates: [-122.4, 37.8],
+ values: [12.5, 8],
+ band_names: ['red', 'nir']
+ });
+ t.equal(parsed.length, 4, 'should format lon/lat plus two bands');
+ t.equal(parsed[2].name, 'red');
+ t.end();
+});
+
+test('#RasterTileLayer -> hover, picking, and extract from loaded tiles', t => {
+ const layer = new RasterTileLayer({id: 'raster-id', dataId: 'stac-data', label: 'Rivers'});
+ layer.config.visConfig.allowHover = true;
+ layer._loadedTiles = [
+ {
+ index: {x: 0, y: 0, z: 0},
+ bbox: {west: -180, south: -85, east: 180, north: 85},
+ data: {
+ images: {
+ imageBands: [{data: new Uint8Array([40]), width: 1, height: 1}]
+ }
+ }
+ }
+ ];
+ layer._identifyContext = {
+ isPMTiles: false,
+ bandCombination: 'single',
+ loadAssetIds: ['red']
+ };
+
+ const hover = layer.getHoverData(null, null, [], null, {index: 0, coordinate: [0, 0]});
+ t.ok(hover.rasterFeatureData, 'hover should return raster feature rows');
+ t.ok(
+ hover.rasterFeatureData.some(row => row.name === 'red'),
+ 'hover includes the sampled band'
+ );
+
+ const hovered = layer.hasHoveredObject({
+ picked: true,
+ layer: {props: {id: `raster-2d-layer-${layer.id}`}}
+ });
+ t.ok(hovered, 'child RasterLayer ids should count as hovered');
+
+ const pmtilesLayer = new RasterTileLayer({id: 'pmtiles-id', dataId: 'pmtiles-data'});
+ const pmtilesLayersDefault = pmtilesLayer.renderLayer({
+ ...createRenderOpts(MOCK_PMTILES_DATASET),
+ idx: 2
+ });
+ t.equal(
+ pmtilesLayersDefault[0]?.props.pickable,
+ false,
+ 'PMTiles should not be pickable by default'
+ );
+ t.equal(pmtilesLayersDefault[0]?.props.idx, 2, 'idx should be forwarded onto the TileLayer');
+
+ pmtilesLayer.config.visConfig.allowHover = true;
+ const pmtilesLayersHoverOn = pmtilesLayer.renderLayer({
+ ...createRenderOpts(MOCK_PMTILES_DATASET),
+ idx: 2
+ });
+ t.equal(
+ pmtilesLayersHoverOn[0]?.props.pickable,
+ true,
+ 'PMTiles should be pickable when allowHover and tooltips are on'
+ );
+
+ pmtilesLayer.config.visConfig.allowHover = false;
+ const pmtilesLayersHoverOff = pmtilesLayer.renderLayer({
+ ...createRenderOpts(MOCK_PMTILES_DATASET),
+ idx: 2
+ });
+ t.equal(
+ pmtilesLayersHoverOff[0]?.props.pickable,
+ false,
+ 'PMTiles should not be pickable when allowHover is off'
+ );
+
+ layer.config.visConfig.allowHover = false;
+ t.equal(
+ layer.hasHoveredObject({
+ picked: true,
+ layer: {props: {id: `raster-2d-layer-${layer.id}`}}
+ }),
+ null,
+ 'should not report hover when allowHover is off'
+ );
+ t.equal(
+ layer.getHoverData(null, null, [], null, {index: 0, coordinate: [0, 0]}),
+ null,
+ 'should not build tooltip rows when allowHover is off'
+ );
+
+ const extracted = layer.extractInsideFeature({
+ type: 'Feature',
+ properties: {shape: 'Rectangle'},
+ geometry: {
+ type: 'Polygon',
+ coordinates: [
+ [
+ [-10, -10],
+ [10, -10],
+ [10, 10],
+ [-10, 10],
+ [-10, -10]
+ ]
+ ]
+ }
+ });
+ t.equal(extracted.kind, 'geojson', 'extract should return geojson stats');
+ t.equal(extracted.rowCount, 1, 'extract should keep the polygon as one feature');
+ t.ok(extracted.features[0].properties.pixel_count > 0, 'extract should count pixels');
+ t.end();
+});
+
+test('#RasterTileLayer -> raster stats sidecar is GeoJSON with bbox rectangle', t => {
+ const geometry = {
+ type: 'Polygon',
+ coordinates: [
+ [
+ [0, 0],
+ [10, 0],
+ [10, 5],
+ [0, 5],
+ [0, 0]
+ ]
+ ]
+ };
+ const sidecar = rasterZonalStatsToSidecar(
+ {
+ pixelCount: 12,
+ bands: {red: {count: 12, min: 1, max: 9, mean: 4, sum: 48}},
+ derived: {count: 12, min: 0.1, max: 0.8, mean: 0.4, sum: 4.8},
+ derivedName: 'NDVI'
+ },
+ {layer: 'Rivers', preset: 'ndvi', geometry}
+ );
+ t.equal(sidecar.type, 'FeatureCollection');
+ t.equal(sidecar.features.length, 1);
+ t.equal(sidecar.features[0].type, 'Feature');
+ t.deepEqual(sidecar.features[0].geometry, geometry);
+ t.equal(sidecar.features[0].properties.layer, 'Rivers');
+ t.equal(sidecar.features[0].properties.pixel_count, 12);
+ t.equal(sidecar.features[0].properties.red_mean, 4);
+ t.equal(sidecar.features[0].properties.ndvi_mean, 0.4);
+ t.equal(sidecar.features[0].properties.shape, 'Rectangle');
+ t.end();
+});
+
+test('#RasterTileLayer -> extract PNG size follows rectangle aspect ratio', t => {
+ const wide = mercatorPixelSizeForBbox([-20, 10, 20, 12], 1000);
+ t.ok(wide.width > wide.height, 'a wide geographic rectangle should export a wide image');
+ t.equal(wide.width, 1000, 'the long side should use the max size');
+
+ const tall = mercatorPixelSizeForBbox([0, 0, 1, 20], 1000);
+ t.ok(tall.height > tall.width, 'a tall geographic rectangle should export a tall image');
+ t.equal(tall.height, 1000, 'the long side should use the max size');
+
+ const square = mercatorPixelSizeForBbox([-1, -1, 1, 1], 512);
+ t.ok(
+ Math.abs(square.width / square.height - 1) < 0.15,
+ 'a square geographic bbox should stay roughly square in mercator near the equator'
+ );
+ t.end();
+});
+
+test('#RasterTileLayer -> non-rectangular polygon export uses lon/lat bbox rectangle', t => {
+ const triangle = {
+ type: 'Feature',
+ properties: {shape: 'Polygon'},
+ geometry: {
+ type: 'Polygon',
+ coordinates: [
+ [
+ [0, 0],
+ [10, 0],
+ [0, 5],
+ [0, 0]
+ ]
+ ]
+ }
+ };
+ const rect = polygonToBboxRectangle(triangle);
+ t.ok(rect, 'should build a bbox rectangle');
+ t.equal(rect.properties.shape, 'Rectangle');
+ t.deepEqual(rect.geometry.coordinates[0], [
+ [0, 0],
+ [10, 0],
+ [10, 5],
+ [0, 5],
+ [0, 0]
+ ]);
+
+ const layer = new RasterTileLayer({id: 'raster-bbox-id', dataId: 'stac-data', label: 'Rivers'});
+ layer._loadedTiles = [
+ {
+ index: {x: 0, y: 0, z: 0},
+ bbox: {west: -180, south: -85, east: 180, north: 85},
+ data: {
+ images: {
+ imageBands: [{data: new Uint8Array([40]), width: 1, height: 1}]
+ }
+ }
+ }
+ ];
+ layer._identifyContext = {
+ isPMTiles: false,
+ bandCombination: 'single',
+ loadAssetIds: ['red']
+ };
+ const extracted = layer.extractInsideFeature(triangle);
+ t.deepEqual(
+ extracted.features[0].geometry.coordinates[0],
+ [
+ [0, 0],
+ [10, 0],
+ [10, 5],
+ [0, 5],
+ [0, 0]
+ ],
+ 'extract should use the lon/lat bbox rectangle, not the triangle'
+ );
+ t.end();
+});
+
+test('#RasterTileLayer -> only image blobs are treated as downloadable PNGs', t => {
+ t.ok(
+ isDownloadableImageBlob({type: 'image/png', size: 12}),
+ 'a non-empty PNG blob should download'
+ );
+ t.notOk(
+ isDownloadableImageBlob({type: 'application/json', size: 80}),
+ 'a JSON error body should not be saved as a PNG'
+ );
+ t.notOk(
+ isDownloadableImageBlob({type: 'image/png', size: 0}),
+ 'an empty image blob should not download'
+ );
+ t.end();
+});
diff --git a/test/node/reducers/vis-state-test.js b/test/node/reducers/vis-state-test.js
index 27f5822db..43a181455 100644
--- a/test/node/reducers/vis-state-test.js
+++ b/test/node/reducers/vis-state-test.js
@@ -6323,6 +6323,71 @@ test('#visStateReducer -> EXTRACT_DATA_FROM_FEATURE empty polygon', t => {
t.end();
});
+test('#visStateReducer -> EXTRACT_DATA_FROM_FEATURE raster awaits clip download', t => {
+ drainTasksForTesting();
+ const layer = {
+ id: 'raster-extract',
+ type: LAYER_TYPES.rasterTile,
+ config: {dataId: 'stac-data', label: 'Africa Farms'},
+ extractInsideFeature: () => ({
+ kind: 'geojson',
+ features: [
+ {
+ type: 'Feature',
+ geometry: mockPolygonFeature.geometry,
+ properties: {pixel_count: 1}
+ }
+ ],
+ rowCount: 1
+ }),
+ downloadClip: () => Promise.resolve({png: true, json: true})
+ };
+ const startState = {
+ ...INITIAL_VIS_STATE,
+ layers: [layer],
+ datasets: {
+ 'stac-data': {
+ id: 'stac-data',
+ fields: [],
+ dataContainer: createDataContainer([])
+ }
+ },
+ editor: {
+ ...INITIAL_VIS_STATE.editor,
+ selectedFeature: mockPolygonFeature
+ }
+ };
+
+ const pendingState = reducer(
+ startState,
+ VisStateActions.extractDataFromFeature({layerId: layer.id})
+ );
+ const downloadTasks = drainTasksForTesting();
+ t.equal(downloadTasks.length, 1, 'Should wait on downloadClip instead of toasting immediately');
+
+ const successAction = succeedTaskInTest(downloadTasks[0], {png: true, json: true});
+ t.ok(
+ JSON.stringify(successAction).includes('Downloaded raster clip image'),
+ 'Should toast success after a PNG is produced'
+ );
+ reducer(pendingState, successAction);
+ drainTasksForTesting();
+
+ const pendingFailState = reducer(
+ startState,
+ VisStateActions.extractDataFromFeature({layerId: layer.id})
+ );
+ const failDownloadTasks = drainTasksForTesting();
+ const failAction = succeedTaskInTest(failDownloadTasks[0], {png: false, json: true});
+ t.ok(
+ JSON.stringify(failAction).includes('Failed to download raster clip image'),
+ 'Should toast an error when no PNG is produced'
+ );
+ reducer(pendingFailState, failAction);
+ drainTasksForTesting();
+ t.end();
+});
+
test('#visStateReducer -> CONVERT_EDITOR_FEATURES_TO_LAYER disabled by config', t => {
initApplicationConfig({enableDrawOnMapSketches: false});
diff --git a/test/node/utils/extract-dataset-utils-test.js b/test/node/utils/extract-dataset-utils-test.js
index 28b830614..ce0c7ea11 100644
--- a/test/node/utils/extract-dataset-utils-test.js
+++ b/test/node/utils/extract-dataset-utils-test.js
@@ -76,6 +76,22 @@ test('extract-dataset-utils -> isExtractableLayer', t => {
),
'vector tile layers are extractable from the loaded tile cache'
);
+ t.ok(
+ isExtractableLayer(
+ {
+ type: LAYER_TYPES.rasterTile,
+ config: {dataId: 'raster'}
+ },
+ {
+ raster: {
+ type: DatasetType.RASTER_TILE,
+ fields: [],
+ dataContainer: createDataContainer([])
+ }
+ }
+ ),
+ 'raster tile layers are extractable from the loaded tile cache'
+ );
t.end();
});