Raster, GeoTIFF and WebGL · Angular, React and OpenLayers

NDVI computed in a raster source

Compute Sentinel-2 NDVI per pixel inside an OpenLayers RasterSource Web Worker using unnormalized GeoTIFFs, lib helpers and getData() lookup.

Kraków's fields and woods in dark green by NDVI, the city centre and the Vistula pale, and NDVI 0.09 for the pointer over the Old Town below the map.
A screenshot of the example. Contains modified Copernicus Sentinel data 2024.

What this example shows

Over Kraków and surrounding fields at [resolution]="40" in UTM zone 34N, red and near-infrared Sentinel-2 GeoTIFF bands are combined pixel by pixel inside a background Web Worker to render an NDVI colour map in an image layer, with live two-decimal NDVI inspection (– outside data) on pointer move or click.

When you need it

When raster analysis requires custom JavaScript branching, lookup tables or third-party numerical functions that go beyond declarative WebGL style operators, OpenLayers’ Raster source executes arbitrary JavaScript per pixel inside worker threads.

Feeding unnormalized raw GeoTIFF bands into aol-source-raster gives worker functions exact physical reflectance values.

The code

The example uses cc-openlayers, my Angular component library for OpenLayers: each aol-… element creates the OpenLayers object it names, updates it from its inputs and disposes of it with the component.

cog-math-raster.shared.ts
import type { Coordinate } from 'ol/coordinate.js';
import type { SourceInfo } from 'ol/source/GeoTIFF.js';

const SCENE =
  'https://sentinel-cogs.s3.us-west-2.amazonaws.com/sentinel-s2-l2a-cogs/34/U/DA/2024/8/S2B_34UDA_20240814_0_L2A';

/** The Main Market Square in the scene's projection, UTM zone 34N (EPSG:32634). */
export const KRAKOW: Coordinate = [423901, 5545999];

/** Red and near infrared, both at 10 m: the first two values of each pixel the operation gets. */
export const SOURCES: SourceInfo[] = [{ url: `${SCENE}/B04.tif` }, { url: `${SCENE}/B08.tif` }];

/** A value of the ramp and its colour. */
export type Stop = [number, [number, number, number]];

/** NDVI values from -0.2 to 0.65 and the colour of each, from grey through yellow to dark green. */
export const RAMP: Stop[] = [
  [-0.2, [191, 191, 191]],
  [-0.1, [219, 219, 219]],
  [0, [255, 255, 224]],
  [0.025, [255, 250, 204]],
  [0.05, [237, 232, 181]],
  [0.075, [222, 217, 156]],
  [0.1, [204, 199, 130]],
  [0.125, [189, 184, 107]],
  [0.15, [176, 194, 97]],
  [0.175, [163, 204, 89]],
  [0.2, [145, 191, 82]],
  [0.25, [128, 179, 71]],
  [0.3, [112, 163, 64]],
  [0.35, [97, 150, 54]],
  [0.4, [79, 138, 46]],
  [0.45, [64, 125, 36]],
  [0.5, [48, 110, 28]],
  [0.55, [33, 97, 18]],
  [0.6, [15, 84, 10]],
  [0.65, [0, 69, 0]],
];

/** What the operation gets from `beforeoperations`. */
export interface NdviData {
  stops: Stop[];
}

/**
 * The functions the raster worker defines under these names before it runs the operation, which calls them by
 * these names as globals: a production build renames the functions of this module, and a name taken from the
 * module would not exist in the worker.
 */
export const WORKER_LIB = {
  /** The `[r, g, b, a]` colour of a value between the ramp's stops; the end colours outside them. */
  colorFromRamp: (value: number, stops: Stop[]): number[] => {
    if (value <= stops[0][0]) return [...stops[0][1], 255];
    for (let i = 1; i < stops.length; i++) {
      const [highValue, high] = stops[i];
      if (value <= highValue) {
        const [lowValue, low] = stops[i - 1];
        const f = (value - lowValue) / (highValue - lowValue);
        return [low[0] + f * (high[0] - low[0]), low[1] + f * (high[1] - low[1]), low[2] + f * (high[2] - low[2]), 255];
      }
    }
    return [...stops[stops.length - 1][1], 255];
  },
};

/* Defined in the raster worker from `WORKER_LIB`. */
declare const colorFromRamp: (typeof WORKER_LIB)['colorFromRamp'];

/** The NDVI of a pixel's red and near-infrared values as a colour of the ramp; transparent outside the data. */
export function ndviToColor(pixels: number[][], data: object): number[] {
  const [red, nir] = pixels[0];
  const sum = nir + red;
  if (!sum) return [0, 0, 0, 0];
  return colorFromRamp((nir - red) / sum, (data as NdviData).stops);
}
cog-math-raster.ts
import { ChangeDetectionStrategy, Component, computed, signal, viewChild } from '@angular/core';
import {
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerImageComponent,
  MapComponent,
  SourceRasterComponent,
  ViewComponent,
} from 'cc-openlayers';
import { SourceGeoTIFFComponent } from 'cc-openlayers/webgl';
import type { MapBrowserEvent } from 'ol';
import type { ViewOptions } from 'ol/View';
import type { RasterSourceEvent } from 'ol/source/Raster';
import { KRAKOW, type NdviData, ndviToColor, RAMP, SOURCES, WORKER_LIB } from './cog-math-raster.shared';

/**
 * NDVI from the red and near-infrared bands of a Sentinel-2 scene over Kraków, calculated per pixel in a worker by
 * a raster source from the raw values of a GeoTIFF source; the values under the pointer are read back from it.
 */
@Component({
  selector: 'app-cog-math-raster',
  imports: [
    DefaultControlComponent,
    DefaultInteractionComponent,
    LayerImageComponent,
    MapComponent,
    SourceGeoTIFFComponent,
    SourceRasterComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px" (pointerMove)="showNdvi($event)" (singleClick)="showNdvi($event)">
      <aol-interaction-default />
      <aol-control-defaults />
      @if (view(); as options) {
        <aol-view
          [projection]="options.projection"
          [resolutions]="options.resolutions"
          [extent]="options.extent"
          [center]="krakow"
          [resolution]="40"
        />
      }
      <aol-layer-image>
        <aol-source-raster [operation]="operation" [lib]="lib" (beforeOperations)="beforeOperations($event)">
          <aol-source-geotiff
            [sources]="sources"
            [normalize]="false"
            attributions="Contains modified Copernicus Sentinel data 2024"
            (viewReady)="view.set($event)"
          />
        </aol-source-raster>
      </aol-layer-image>
    </aol-map>
    <div class="example-controls">
      <span>
        NDVI <output>{{ ndvi() }}</output>
      </span>
    </div>
  `,
})
export class CogMathRaster {
  readonly view = signal<ViewOptions | undefined>(undefined);
  protected readonly krakow = KRAKOW;
  protected readonly operation = ndviToColor;
  protected readonly lib = WORKER_LIB;
  protected readonly raster = viewChild.required(SourceRasterComponent);
  protected readonly value = signal<string | undefined>(undefined);
  protected readonly ndvi = computed(() => this.value() ?? '–');

  protected readonly sources = SOURCES;

  /** Hands the ramp to the operation. */
  protected beforeOperations(event: Pick<RasterSourceEvent, 'data'>): void {
    const data: NdviData = event.data;
    data.stops = RAMP;
  }

  /** Calculates the NDVI of the raw values under the pointer or a click; none outside the data. */
  protected showNdvi(event: MapBrowserEvent): void {
    const [red, nir] = this.raster().instance.getData(event.coordinate)?.[0] ?? [0, 0];
    const sum = nir + red;
    this.value.set(sum ? ((nir - red) / sum).toFixed(2) : undefined);
  }
}

Architecture and OpenLayers mechanics

aol-layer-image wraps aol-source-raster, which takes an aol-source-geotiff (B04.tif and B08.tif with [normalize]="false") as its input. Because worker threads run in an isolated scope serialized from function source text, helper colorFromRamp is injected via [lib]="lib" and the colour RAMP array is attached per frame on (beforeOperations).

Worker function ndviToColor computes (nir - red) / (nir + red) (leaving pixels transparent when nir + red === 0), while showNdvi reads raw input tuple values on the main thread via this.raster().instance.getData(event.coordinate)?.[0].

How it works

  • aol-source-raster consumes an aol-source-geotiff of B04.tif and B08.tif configured with [normalize]="false" for raw reflectance values.
  • ndviToColor evaluates per-pixel NDVI in a worker using colorFromRamp supplied through [lib]="lib", keeping zero-sum pixels transparent.
  • beforeOperations copies RAMP into event.data ahead of each worker pass.
  • showNdvi inspects this.raster().instance.getData(event.coordinate)?.[0] on pointer moves and clicks to display live NDVI.

Pitfalls

  • Functions serialized into a Raster worker cannot close over outer module imports or component fields—every helper function must be passed in lib and every runtime parameter in beforeOperations event.data.
  • CPU worker operations recompute the entire viewport after each settled pan or zoom; prefer GPU WebGL style expressions (cog-math) whenever standard band arithmetic suffices.

The same feature in the OpenLayers examples .

Background: state and lifecycle of maps in Angular with OpenLayers, which the components of cc-openlayers take care of.