Projections · Angular, React and OpenLayers

Raster reprojection between eight projections

Reproject OpenStreetMap, Polish EPSG:2180 WMTS, Arctic polar maps and NASA WGS84 relief across eight view projections with triangle debug edges.

GUGiK's topographic map of southern and central Poland in the Polish 1992 grid, from Zielona Góra and Wrocław to Lublin and Przemyśl, half-transparent over OpenStreetMap, which shows beyond the border, with the base map, overlay and view projection selects below.
A screenshot of the example. Topographic map © GUGiK. Map data © OpenStreetMap contributors.

What this example shows

Centred on Kraków, three selectors let you combine two base layers (OpenStreetMap and NASA EPSG:4326 relief) with four thematic overlays (including GUGiK’s EPSG:2180 topographic WMTS and polar maps) inside any of eight target View projections—from Web Mercator and WGS 84 to Polish 1992 (EPSG:2180), Polish 2000, Mollweide and UTM—with a checkbox to draw OpenLayers’ internal reprojection triangulation mesh.

When you need it

National spatial data infrastructures publish authoritative rasters in local planar grids (EPSG:2180, EPSG:27700, EPSG:2056) that must be overlaid seamlessly onto global Web Mercator or polar projections without server-side warping.

Inspecting the live triangulation mesh (Render reprojection edges) shows exactly how OpenLayers subdivides curved grid cells and how reprojectionErrorThreshold trades triangle count against pixel accuracy.

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.

reprojection.shared.ts
import type { Extent } from 'ol/extent.js';
import { fromLonLat, get as getProjection, transformExtent } from 'ol/proj.js';
import { createXYZ } from 'ol/tilegrid.js';
import TileGrid from 'ol/tilegrid/TileGrid.js';
import type WMTSTileGrid from 'ol/tilegrid/WMTS.js';
import { loadProj4, PL_DEFINITIONS, registerProjectionDefinitions } from 'cc-openlayers/core';
import { readWmtsCapabilities, type WmtsLayerDescription, wmtsTileGrid } from 'cc-openlayers/services';

/** The view projections, with the proj4 definitions and extents of those OpenLayers does not know itself. */
export const PROJECTIONS: readonly { code: string; label: string; definition?: string; extent?: Extent }[] = [
  { code: 'EPSG:3857', label: 'Spherical Mercator (EPSG:3857)' },
  { code: 'EPSG:4326', label: 'WGS 84 (EPSG:4326)' },
  {
    code: 'ESRI:54009',
    label: 'Mollweide (ESRI:54009)',
    definition: '+proj=moll +lon_0=0 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs',
    extent: [-18e6, -9e6, 18e6, 9e6],
  },
  {
    code: 'EPSG:2180',
    label: 'Polish 1992 grid (EPSG:2180)',
    definition: PL_DEFINITIONS['EPSG:2180'],
    extent: [144693.28, 125837.02, 876500.36, 908411.19],
  },
  {
    code: 'EPSG:2178',
    label: 'Polish 2000 grid, zone 7 (EPSG:2178)',
    definition: PL_DEFINITIONS['EPSG:2178'],
    extent: [7390450.41, 5439217.73, 7609549.59, 6047705.96],
  },
  {
    code: 'EPSG:3035',
    label: 'Europe Equal Area (EPSG:3035)',
    definition:
      '+proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs',
    extent: [-146473.11, 196541.46, 7824928.56, 6971477.48],
  },
  {
    code: 'EPSG:3413',
    label: 'NSIDC Polar Stereographic North (EPSG:3413)',
    definition: '+proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs',
    extent: [-4194304, -4194304, 4194304, 4194304],
  },
  {
    code: 'EPSG:32634',
    label: 'WGS 84 / UTM zone 34N (EPSG:32634)',
    definition: '+proj=utm +zone=34 +datum=WGS84 +units=m +no_defs',
    extent: [166021.44, 0, 833978.56, 9329005.18],
  },
];

/** The base maps the first selector offers. */
export const BASE_LAYERS = [
  { id: 'osm', label: 'OSM (EPSG:3857)' },
  { id: 'wms4326', label: 'WMS (EPSG:4326)' },
];

/** The overlay maps the second selector offers. */
export const OVERLAY_LAYERS = [
  { id: 'topo', label: 'Topographic map of Poland (EPSG:2180)' },
  { id: 'orto', label: 'Orthophoto WMS (EPSG:2178)' },
  { id: 'arctic', label: 'NASA Arctic WMTS (EPSG:3413)' },
  { id: 'parks', label: 'Protected areas of Poland (EPSG:3857)' },
];

/** Resolutions of Spherical Mercator's 22 zoom levels. */
const MERCATOR_RESOLUTIONS = Array.from({ length: 22 }, (_, level) => 40075016.68557849 / 256 / 2 ** level);

/** A view of the chosen projection on Kraków, kept within the projection's extent. */
export function viewFor(code: string): { code: string; center: number[]; extent: Extent | undefined } {
  const projection = getProjection(code);
  return {
    code,
    center: fromLonLat([19.9373, 50.0617], projection ?? undefined),
    extent: projection?.getExtent() ?? undefined,
  };
}

/** The topographic map's extent in a view of the whole world, so that it is drawn only once. */
export function topoExtentFor(code: string): Extent | undefined {
  const view = getProjection(code);
  const grid = getProjection('EPSG:2180');
  return view?.isGlobal() && grid ? transformExtent(grid.getExtent(), grid, view, 2) : undefined;
}

/** The tile grid of WGS 84 before reprojection. */
export function createWgs84Grid(): TileGrid {
  return createXYZ({ extent: [-180, -90, 180, 90], maxResolution: 360 / 512, maxZoom: 10 });
}

/** A grid of Spherical Mercator over Poland, with tiles twice as wide as they are high. */
export function createParksGrid(): TileGrid {
  return new TileGrid({
    extent: [1566265.24, 6274861.39, 2688365.7, 7330875.09],
    resolutions: MERCATOR_RESOLUTIONS,
    tileSize: [512, 256],
  });
}

/** A WMTS layer with the tile grid its matrix set describes. */
export interface WmtsLayerWithGrid {
  readonly layer: WmtsLayerDescription;
  readonly grid: WMTSTileGrid;
}

async function fetchText(url: string): Promise<string> {
  const response = await fetch(url);
  if (!response.ok) throw new Error(`${url}: ${response.status}`);
  return response.text();
}

/** The WMS sources of the base and overlay maps: address, parameters and attribution. */
export const WMS_SOURCES = {
  wgs84: {
    url: 'https://gibs.earthdata.nasa.gov/wms/epsg4326/best/wms.cgi',
    params: { LAYERS: 'BlueMarble_ShadedRelief_Bathymetry', VERSION: '1.1.1' },
    attributions: 'NASA Blue Marble, GIBS',
  },
  orto: {
    url: 'https://mapy.geoportal.gov.pl/wss/service/PZGIK/ORTO/WMS/StandardResolution',
    params: { LAYERS: 'Raster', FORMAT: 'image/jpeg', VERSION: '1.1.1' },
    attributions: 'Orthophoto: GUGiK',
  },
  parks: {
    url: 'https://sdi.gdos.gov.pl/wms',
    params: { LAYERS: 'GDOS:ParkiKrajobrazowe,GDOS:Rezerwaty' },
    attributions: 'Protected areas: GDOŚ',
  },
};

/** The attributions of the two WMTS maps, whose addresses the capabilities give. */
export const WMTS_ATTRIBUTIONS = { topo: 'Topographic map: GUGiK', arctic: 'NASA GIBS, OpenStreetMap' };

/**
 * Loads proj4 and the WMTS capabilities, registers the projections and reads the topographic and Arctic layers;
 * rejects when a capabilities file cannot be fetched.
 */
export async function loadReprojectionLayers(): Promise<{ topo: WmtsLayerWithGrid; arctic: WmtsLayerWithGrid }> {
  const [proj4, topoXml, arcticXml] = await Promise.all([
    loadProj4(),
    fetchText('assets/reprojection/topo-wmts.xml'),
    fetchText('assets/reprojection/arctic-wmts.xml'),
  ]);
  registerProjectionDefinitions(
    proj4,
    Object.fromEntries(PROJECTIONS.flatMap(({ code, definition }) => (definition ? [[code, definition]] : [])))
  );
  for (const { code, extent } of PROJECTIONS) if (extent) getProjection(code)?.setExtent(extent);
  // The topographic map's capabilities give the corners of the 1992 grid north first.
  const [topo] = readWmtsCapabilities(topoXml, 'https://mapy.geoportal.gov.pl/wss/service/WMTS/guest/wmts/TOPO', {
    preferredProjections: ['EPSG:2180'],
    northEastProjections: ['EPSG:2180'],
  }).layers;
  const [arctic] = readWmtsCapabilities(arcticXml, 'https://gibs.earthdata.nasa.gov/wmts/epsg3413/best/wmts.cgi', {
    preferredProjections: ['EPSG:3413'],
  }).layers;
  return {
    topo: { layer: topo, grid: wmtsTileGrid(topo, topo.projection) },
    arctic: { layer: arctic, grid: wmtsTileGrid(arctic, arctic.projection) },
  };
}
reprojection.ts
import { ChangeDetectionStrategy, Component, computed, inject, PendingTasks, signal } from '@angular/core';
import type WMTSTileGrid from 'ol/tilegrid/WMTS';
import {
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerTileComponent,
  MapComponent,
  SourceOsmComponent,
  SourceTileWMSComponent,
  SourceTileWMTSComponent,
  ViewComponent,
} from 'cc-openlayers';
import type { WmtsLayerDescription } from 'cc-openlayers/services';
import {
  BASE_LAYERS,
  createParksGrid,
  createWgs84Grid,
  loadReprojectionLayers,
  OVERLAY_LAYERS,
  PROJECTIONS,
  topoExtentFor,
  viewFor,
  WMS_SOURCES,
  WMTS_ATTRIBUTIONS,
} from './reprojection.shared';

/**
 * Raster maps in several projections, reprojected on the client into the projection chosen for the view: tiles of
 * OpenStreetMap or NASA's shaded relief (WGS 84) below the topographic map of Poland (a WMTS in the Polish 1992
 * grid), the orthophoto of Kraków (a WMS in the Polish 2000 grid), NASA's Arctic land mask (a WMTS in the polar
 * stereographic projection) or Poland's protected areas (a WMS tiled on a grid of its own). Each new view starts
 * on Kraków; the reprojection triangles can be outlined.
 */
@Component({
  selector: 'app-reprojection',
  imports: [
    DefaultControlComponent,
    DefaultInteractionComponent,
    LayerTileComponent,
    MapComponent,
    SourceOsmComponent,
    SourceTileWMSComponent,
    SourceTileWMTSComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    @if (ready()) {
      <aol-map height="480px">
        <aol-interaction-default />
        <aol-control-defaults />
        <!-- Every projection gets a view of its own, as on the original page. -->
        @for (view of [view()]; track view.code) {
          <aol-view [projection]="view.code" [center]="view.center" [zoom]="1" [extent]="view.extent" />
        }
        @switch (base()) {
          @case ('osm') {
            <aol-layer-tile [zIndex]="0">
              <aol-source-osm [renderReprojectionEdges]="edges()" />
            </aol-layer-tile>
          }
          @case ('wms4326') {
            <aol-layer-tile [zIndex]="0">
              <aol-source-tilewms
                [url]="wms.wgs84.url"
                crossOrigin=""
                [params]="wms.wgs84.params"
                projection="EPSG:4326"
                [tileGrid]="wgs84Grid"
                [reprojectionErrorThreshold]="2"
                [renderReprojectionEdges]="edges()"
                [attributions]="wms.wgs84.attributions"
              />
            </aol-layer-tile>
          }
        }
        @switch (overlay()) {
          @case ('topo') {
            <aol-layer-tile [zIndex]="1" [opacity]="0.7" [extent]="topoExtent()">
              <aol-source-tilewmts
                [url]="topo.url"
                [requestEncoding]="topo.requestEncoding"
                [layer]="topo.identifier"
                [style]="topo.style"
                [format]="topo.format"
                [matrixSet]="topo.matrixSet"
                [projection]="topo.projection"
                [tileGrid]="topoGrid"
                crossOrigin=""
                [wrapX]="false"
                [renderReprojectionEdges]="edges()"
                [attributions]="attributions.topo"
              />
            </aol-layer-tile>
          }
          @case ('orto') {
            <aol-layer-tile [zIndex]="1" [opacity]="0.7">
              <aol-source-tilewms
                [url]="wms.orto.url"
                crossOrigin="anonymous"
                [params]="wms.orto.params"
                projection="EPSG:2178"
                [renderReprojectionEdges]="edges()"
                [attributions]="wms.orto.attributions"
              />
            </aol-layer-tile>
          }
          @case ('arctic') {
            <aol-layer-tile [zIndex]="1" [opacity]="0.7">
              <aol-source-tilewmts
                [url]="arctic.url"
                [requestEncoding]="arctic.requestEncoding"
                [layer]="arctic.identifier"
                [style]="arctic.style"
                [format]="arctic.format"
                [matrixSet]="arctic.matrixSet"
                [projection]="arctic.projection"
                [tileGrid]="arcticGrid"
                crossOrigin=""
                [wrapX]="false"
                [renderReprojectionEdges]="edges()"
                [attributions]="attributions.arctic"
              />
            </aol-layer-tile>
          }
          @case ('parks') {
            <aol-layer-tile [zIndex]="1" [opacity]="0.7">
              <aol-source-tilewms
                [url]="wms.parks.url"
                crossOrigin=""
                [params]="wms.parks.params"
                serverType="geoserver"
                projection="EPSG:3857"
                [tileGrid]="parksGrid"
                [renderReprojectionEdges]="edges()"
                [attributions]="wms.parks.attributions"
              />
            </aol-layer-tile>
          }
        }
      </aol-map>
      <form class="example-controls">
        <label>
          Base map
          <select id="base-layer" (change)="base.set(value($event))">
            @for (layer of baseLayers; track layer.id) {
              <option [value]="layer.id" [selected]="layer.id === base()">{{ layer.label }}</option>
            }
          </select>
        </label>
        <label>
          Overlay map
          <select id="overlay-layer" (change)="overlay.set(value($event))">
            @for (layer of overlayLayers; track layer.id) {
              <option [value]="layer.id" [selected]="layer.id === overlay()">{{ layer.label }}</option>
            }
          </select>
        </label>
        <label>
          View projection
          <select id="view-projection" (change)="projection.set(value($event))">
            @for (projection of projections; track projection.code) {
              <option [value]="projection.code" [selected]="projection.code === this.projection()">
                {{ projection.label }}
              </option>
            }
          </select>
        </label>
        <label>
          <input
            id="render-edges"
            type="checkbox"
            [checked]="edges()"
            (change)="edges.set($any($event.target).checked)"
          />
          Render reprojection edges
        </label>
      </form>
    }
  `,
})
export class Reprojection {
  /** True once proj4 and the WMTS capabilities have loaded. */
  readonly ready = signal(false);
  readonly base = signal('osm');
  readonly overlay = signal('topo');
  readonly projection = signal('EPSG:2180');
  readonly edges = signal(false);
  protected readonly projections = PROJECTIONS;
  protected readonly baseLayers = BASE_LAYERS;
  protected readonly overlayLayers = OVERLAY_LAYERS;
  protected readonly wms = WMS_SOURCES;
  protected readonly attributions = WMTS_ATTRIBUTIONS;

  /** A view of the chosen projection on Kraków, kept within the projection's extent. */
  protected readonly view = computed(() => viewFor(this.projection()));

  /** The topographic map's extent in a view of the whole world, so that it is drawn only once. */
  protected readonly topoExtent = computed(() => topoExtentFor(this.projection()));

  /** The tile grid of WGS 84 before reprojection. */
  protected readonly wgs84Grid = createWgs84Grid();
  /** A grid of Spherical Mercator over Poland, with tiles twice as wide as they are high. */
  protected readonly parksGrid = createParksGrid();

  protected topo!: WmtsLayerDescription;
  protected topoGrid!: WMTSTileGrid;
  protected arctic!: WmtsLayerDescription;
  protected arcticGrid!: WMTSTileGrid;

  constructor() {
    void inject(PendingTasks).run(async () => {
      try {
        const { topo, arctic } = await loadReprojectionLayers();
        [this.topo, this.topoGrid] = [topo.layer, topo.grid];
        [this.arctic, this.arcticGrid] = [arctic.layer, arctic.grid];
        this.ready.set(true);
      } catch (error) {
        console.error('The map layers could not be loaded', error);
      }
    });
  }

  protected value(event: Event): string {
    return (event.target as HTMLSelectElement).value;
  }
}

Architecture and OpenLayers mechanics

PROJECTIONS registers custom CRS definitions via registerProjectionDefinitions with explicit projection extents. GUGiK’s EPSG:2180 topographic WMTS parses its local capabilities XML using northEastProjections: ['EPSG:2180'] so northing-first TopLeftCorner coordinates (850000 100000) are swapped properly, bounded by topoExtent so Poland does not repeat globally.

Each projection switch mounts a fresh view via @for over [view()] centred on fromLonLat([19.9373, 50.0617], projection ?? undefined), while NASA’s wgs84Grid layer sets [reprojectionErrorThreshold]="2" to demonstrate coarser, larger triangles.

How it works

  • PROJECTIONS registers every proj4 definition through registerProjectionDefinitions, then a separate loop applies each grid’s extent with setExtent.
  • northEastProjections: ['EPSG:2180'] swaps GUGiK’s northing-first WMTS matrix origins into [easting, northing] order.
  • fromLonLat([19.9373, 50.0617], projection ?? undefined) centres each newly created @for [view()] on Kraków.
  • topoExtent fences the Polish topographic WMTS to its valid national area on global views.
  • [reprojectionErrorThreshold]="2" on NASA’s EPSG:4326 WMS source, which uses the wgs84Grid tile grid, relaxes error tolerance to 2 pixels and produces larger visible triangles.

Pitfalls

  • Polish EPSG:2180 orders axes North then East (850000, 100000): reading WMTS TopLeftCorner values as East-first without northEastProjections (or +axis=neu) misplaces every tile thousands of kilometres from Poland.
  • Always assign a valid extent to custom proj4 projections—without one, OpenLayers guesses a huge global extent that makes initial zoom levels unusable on national grids.

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.