Raster, GeoTIFF and WebGL · Angular, React and OpenLayers

Flooding the terrain up to a water level

Simulate interactive terrain flooding around Kraków from non-interpolated Terrarium DEM tiles in an OpenLayers RasterSource with live readouts.

OpenStreetMap of Kraków with the Vistula valley east of the city flooded light blue up to 200 m, Elevation at pointer 219 m for the Main Square, and buttons for four towns below.
A screenshot of the example. Elevation: Terrain Tiles on AWS (Mapzen); Europe terrain data produced using Copernicus data and information funded by the European Union - EU-DEM layers; global GMTED2010 and SRTM terrain data courtesy of the U.S. Geological Survey. Map data © OpenStreetMap contributors.

What this example shows

Over OpenStreetMap of Kraków and the Vistula valley at zoom 11, a Water level slider (180 to 260 m above sea level, starting at 200 m) floods every lowland area at or below the chosen elevation in translucent light blue, paired with a live pointer elevation readout (– before interaction) and quick-jump buttons for four regional towns.

When you need it

River-basin flood planners, reservoir engineers, coastal resilience portals and geography educators use interactive water-level sliders to visualise inundation zones immediately in the browser.

Decoding global RGB-encoded elevation tiles client-side eliminates server-side flood-polygon precomputation for arbitrary water levels.

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.

sea-level.shared.ts
export const ATTRIBUTIONS =
  'Elevation: <a href="https://github.com/tilezen/joerd/blob/master/docs/attribution.md" target="_blank">Terrain Tiles</a>';

export interface Place {
  name: string;
  lon: number;
  lat: number;
}

/** The Vistula valley and the neighbouring towns, which the buttons move the map to. */
export const PLACES: Place[] = [
  { name: 'Kraków', lon: 19.9368, lat: 50.0614 },
  { name: 'Tarnów', lon: 20.9877, lat: 50.0121 },
  { name: 'Oświęcim', lon: 19.2238, lat: 50.0343 },
  { name: 'Nowy Sącz', lon: 20.6877, lat: 49.6249 },
];

export interface FloodData {
  level: number;
}

/**
 * Paints the pixels whose elevation is at or below the water level light blue and hides the others. The tiles
 * are Terrarium-encoded: elevation in metres is `R * 256 + G + B / 256 - 32768`.
 */
export function flood(pixels: number[][], data: FloodData): number[] {
  const pixel = pixels[0];
  if (pixel[3]) {
    const height = pixel[0] * 256 + pixel[1] + pixel[2] / 256 - 32768;
    if (height <= data.level) {
      pixel[0] = 134;
      pixel[1] = 203;
      pixel[2] = 249;
      pixel[3] = 255;
    } else {
      pixel[3] = 0;
    }
  }
  return pixel;
}

/** The elevation in metres a tile pixel encodes (see `flood`), rounded; undefined where the pixel is transparent. */
export function elevationOf(pixel: ArrayLike<number> | undefined): number | undefined {
  return pixel?.[3] ? Math.round(pixel[0] * 256 + pixel[1] + pixel[2] / 256 - 32768) : undefined;
}
sea-level.ts
import { ChangeDetectionStrategy, Component, computed, signal, viewChild } from '@angular/core';
import type { MapBrowserEvent } from 'ol';
import { fromLonLat } from 'ol/proj';
import type { RasterSourceEvent } from 'ol/source/Raster';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerImageComponent,
  LayerTileComponent,
  MapComponent,
  SourceOsmComponent,
  SourceRasterComponent,
  SourceXYZComponent,
  ViewComponent,
} from 'cc-openlayers';
import { ATTRIBUTIONS, elevationOf, flood, type FloodData, PLACES, type Place } from './sea-level.shared';

/**
 * A raster source that floods the terrain below the chosen elevation, read from Terrarium elevation tiles without
 * interpolation, as blending neighbouring pixels would mix the colours that encode their heights; the elevation
 * under the pointer is read back from its input.
 */
@Component({
  selector: 'app-sea-level',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    LayerImageComponent,
    LayerTileComponent,
    MapComponent,
    SourceOsmComponent,
    SourceRasterComponent,
    SourceXYZComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px" (pointerMove)="showElevation($event)" (singleClick)="showElevation($event)">
      <aol-interaction-default />
      <aol-control-defaults />
      <aol-view [zoom]="11">
        <aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" />
      </aol-view>
      <aol-layer-tile><aol-source-osm /></aol-layer-tile>
      <aol-layer-image [opacity]="0.6">
        <aol-source-raster [operation]="operation" (beforeOperations)="beforeOperations($event)">
          <aol-source-xyz
            url="https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"
            [attributions]="attributions"
            crossOrigin="anonymous"
            [interpolate]="false"
            [maxZoom]="15"
          />
        </aol-source-raster>
      </aol-layer-image>
    </aol-map>
    <div class="example-controls">
      <span>
        Elevation at pointer <output>{{ elevation() }}</output>
      </span>
      <label>
        Water level
        <input
          type="range"
          min="180"
          max="260"
          [value]="level()"
          (input)="level.set(number($event)); raster().instance.changed()"
        />
        <output>{{ level() }}</output>
        m above sea level
      </label>
      @for (place of places; track place.name) {
        <button type="button" (click)="goTo(place)">{{ place.name }}</button>
      }
    </div>
  `,
})
export class SeaLevel {
  readonly level = signal(200);
  protected readonly metres = signal<number | undefined>(undefined);
  protected readonly elevation = computed(() => {
    const metres = this.metres();
    return metres === undefined ? '–' : `${metres} m`;
  });
  protected readonly attributions = ATTRIBUTIONS;
  protected readonly operation = flood;
  protected readonly places = PLACES;

  private readonly map = viewChild.required(MapComponent);
  protected readonly raster = viewChild.required(SourceRasterComponent);

  /** Hands the water level to the pixel operation. */
  protected beforeOperations(event: Pick<RasterSourceEvent, 'data'>): void {
    const data: FloodData = event.data;
    data.level = this.level();
  }

  /** The elevation under the pointer or a click, decoded as in `flood` from the tile pixel the operation gets there. */
  protected showElevation(event: MapBrowserEvent): void {
    const pixel = this.raster().instance.getData(event.coordinate)?.[0];
    this.metres.set(elevationOf(pixel));
  }

  protected goTo(place: Place): void {
    const view = this.map().instance.getView();
    view.setCenter(fromLonLat([place.lon, place.lat]));
    view.setZoom(11);
  }

  protected number(event: Event): number {
    return (event.target as HTMLInputElement).valueAsNumber;
  }
}

Architecture and OpenLayers mechanics

An aol-layer-image ([opacity]="0.6") wraps aol-source-raster over aol-source-xyz pointing at AWS Terrarium PNG tiles (crossOrigin="anonymous", [maxZoom]="15", and critically [interpolate]="false"). Worker function flood decodes each pixel via R * 256 + G + B / 256 - 32768 metres—painting pixels <= data.level light blue and higher ground transparent.

Scrubbing the slider updates level and calls changed() on the raster source (passing data.level via (beforeOperations)), while showElevation decodes the rounded height under the pointer from getData(event.coordinate).

How it works

  • flood decodes Terrarium RGB bytes (R * 256 + G + B / 256 - 32768 m) and colours terrain at or below data.level light blue.
  • [interpolate]="false" enforces nearest-neighbour tile sampling so RGB-encoded byte channels are never blended across pixel boundaries.
  • Dragging the 180–260 m slider (initial 200 m) updates level and invokes changed() on aol-source-raster.
  • showElevation decodes raw input height from getData(event.coordinate) on pointer move and click, alongside four town preset buttons.

Pitfalls

  • Leaving bilinear interpolation enabled on RGB-encoded Terrarium tiles blends high-order R and low-order G/B channels between adjacent pixels (for instance turning the boundary between 255 m and 256 m into false 128 m or 384 m rings)—always set [interpolate]="false".
  • Because the Terrarium pyramid stops at [maxZoom]="15", zooming closer than level 15 enlarges level-15 elevation pixels cleanly.

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.