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.

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.tsimport 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.tsimport { 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;
}
} The React version uses the library's React adapter, cc-openlayers/react: each component creates the OpenLayers object it names when it mounts, updates it from its props and disposes of it when it unmounts.
reprojection.react.tsximport { useEffect, useMemo, useState } from 'react';
import {
DefaultControls,
DefaultInteractions,
Map,
OSMSource,
TileLayer,
TileWMSSource,
View,
WMTSSource,
} from 'cc-openlayers/react';
import {
BASE_LAYERS,
createParksGrid,
createWgs84Grid,
loadReprojectionLayers,
OVERLAY_LAYERS,
PROJECTIONS,
topoExtentFor,
viewFor,
WMS_SOURCES,
WMTS_ATTRIBUTIONS,
type WmtsLayerWithGrid,
} from './reprojection.shared';
/** The tile grid of WGS 84 before reprojection. */
const WGS84_GRID = createWgs84Grid();
/** A grid of Spherical Mercator over Poland, with tiles twice as wide as they are high. */
const PARKS_GRID = createParksGrid();
/** The WMTS source of a layer read from capabilities, on the tile grid they describe. */
function CapabilitiesSource({
description,
edges,
attributions,
}: {
description: WmtsLayerWithGrid;
edges: boolean;
attributions: string;
}) {
const { layer, grid } = description;
return (
<WMTSSource
url={layer.url}
requestEncoding={layer.requestEncoding}
layer={layer.identifier}
style={layer.style}
format={layer.format}
matrixSet={layer.matrixSet}
projection={layer.projection}
tileGrid={grid}
crossOrigin=""
wrapX={false}
renderReprojectionEdges={edges}
attributions={attributions}
/>
);
}
/**
* 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.
*/
export function Reprojection() {
/** The topographic and Arctic layers, once proj4 and the WMTS capabilities have loaded. */
const [layers, setLayers] = useState<{ topo: WmtsLayerWithGrid; arctic: WmtsLayerWithGrid } | null>(null);
const [base, setBase] = useState('osm');
const [overlay, setOverlay] = useState('topo');
const [projection, setProjection] = useState('EPSG:2180');
const [edges, setEdges] = useState(false);
useEffect(() => {
let current = true;
void loadReprojectionLayers().then(
(loaded) => current && setLayers(loaded),
(error: unknown) => console.error('The map layers could not be loaded', error)
);
return () => {
current = false;
};
}, []);
/** A view of the chosen projection on Kraków, kept within the projection's extent. */
const view = useMemo(() => (layers ? viewFor(projection) : null), [layers, projection]);
/** The topographic map's extent in a view of the whole world, so that it is drawn only once. */
const topoExtent = useMemo(() => (layers ? topoExtentFor(projection) : undefined), [layers, projection]);
if (!layers || !view) return null;
return (
<>
<Map height="480px">
<DefaultInteractions />
<DefaultControls />
{/* Every projection gets a view of its own, as on the original page. */}
<View key={view.code} projection={view.code} center={view.center} zoom={1} extent={view.extent} />
{base === 'osm' && (
<TileLayer zIndex={0}>
<OSMSource renderReprojectionEdges={edges} />
</TileLayer>
)}
{base === 'wms4326' && (
<TileLayer zIndex={0}>
<TileWMSSource
url={WMS_SOURCES.wgs84.url}
crossOrigin=""
params={WMS_SOURCES.wgs84.params}
projection="EPSG:4326"
tileGrid={WGS84_GRID}
reprojectionErrorThreshold={2}
renderReprojectionEdges={edges}
attributions={WMS_SOURCES.wgs84.attributions}
/>
</TileLayer>
)}
{overlay === 'topo' && (
<TileLayer zIndex={1} opacity={0.7} extent={topoExtent}>
<CapabilitiesSource description={layers.topo} edges={edges} attributions={WMTS_ATTRIBUTIONS.topo} />
</TileLayer>
)}
{overlay === 'orto' && (
<TileLayer zIndex={1} opacity={0.7}>
<TileWMSSource
url={WMS_SOURCES.orto.url}
crossOrigin="anonymous"
params={WMS_SOURCES.orto.params}
projection="EPSG:2178"
renderReprojectionEdges={edges}
attributions={WMS_SOURCES.orto.attributions}
/>
</TileLayer>
)}
{overlay === 'arctic' && (
<TileLayer zIndex={1} opacity={0.7}>
<CapabilitiesSource description={layers.arctic} edges={edges} attributions={WMTS_ATTRIBUTIONS.arctic} />
</TileLayer>
)}
{overlay === 'parks' && (
<TileLayer zIndex={1} opacity={0.7}>
<TileWMSSource
url={WMS_SOURCES.parks.url}
crossOrigin=""
params={WMS_SOURCES.parks.params}
serverType="geoserver"
projection="EPSG:3857"
tileGrid={PARKS_GRID}
renderReprojectionEdges={edges}
attributions={WMS_SOURCES.parks.attributions}
/>
</TileLayer>
)}
</Map>
<form className="example-controls">
<label>
Base map
<select id="base-layer" value={base} onChange={(event) => setBase(event.target.value)}>
{BASE_LAYERS.map((layer) => (
<option key={layer.id} value={layer.id}>
{layer.label}
</option>
))}
</select>
</label>
<label>
Overlay map
<select id="overlay-layer" value={overlay} onChange={(event) => setOverlay(event.target.value)}>
{OVERLAY_LAYERS.map((layer) => (
<option key={layer.id} value={layer.id}>
{layer.label}
</option>
))}
</select>
</label>
<label>
View projection
<select id="view-projection" value={projection} onChange={(event) => setProjection(event.target.value)}>
{PROJECTIONS.map((option) => (
<option key={option.code} value={option.code}>
{option.label}
</option>
))}
</select>
</label>
<label>
<input
id="render-edges"
type="checkbox"
checked={edges}
onChange={(event) => setEdges(event.target.checked)}
/>
Render reprojection edges
</label>
</form>
</>
);
}reprojection.shared.tsimport 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) },
};
}How the React version works
OpenStreetMap or NASA's relief as the base, with a Polish topographic map, an orthophoto, an Arctic land mask or protected areas over it, reprojected in the browser into one of eight view projections, from Web Mercator to UTM, with the reprojection edges on request.
What both versions share
OpenLayers renders the map and handles the interactions; the cc-openlayers/core layer gives both adapters the same view binding (MapViewBinding) and the same conversion of coordinates from EPSG:4326 to the map's projection. Both versions import the eight projections with their proj4 definitions and extents, the layer lists, the WMS sources, the WMTS attributions, viewFor, topoExtentFor, the tile grids and loadReprojectionLayers, which loads proj4, registers the projections and reads both WMTS capabilities documents and reports a failed load, from the example's .shared.ts file, so the logic exists once.
From Angular to React
| Angular | React |
|---|---|
PendingTasks.run in the constructor and @if (ready()) | a useEffect that calls loadReprojectionLayers() and keeps the result in useState; return null until it arrives |
computed view and topographic extent | useMemo |
@for (view of [view()]; track view.code), a new view per projection | <View key={view.code}>, which React replaces when the key changes |
@switch over the base and the overlay | base === … and overlay === … conditions |
| the WMTS source written out twice in the template | a local CapabilitiesSource component for both capabilities layers |
[renderReprojectionEdges]="edges()" on every source | renderReprojectionEdges={edges} |
Who creates, updates and disposes
Map creates the ol/Map in useLayoutEffect and disposes of it on unmount; each layer, source and interaction component adds its object to the parent it gets from context and removes it in its effect's cleanup, as ngOnDestroy does in Angular. The effect's cleanup sets a flag that drops a late result, so the first of the two StrictMode runs changes nothing; the registered projections stay registered, as they do in Angular.
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
PROJECTIONSregisters everyproj4definition throughregisterProjectionDefinitions, 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.topoExtentfences the Polish topographic WMTS to its valid national area on global views.[reprojectionErrorThreshold]="2"on NASA’sEPSG:4326WMS source, which uses thewgs84Gridtile grid, relaxes error tolerance to 2 pixels and produces larger visible triangles.
Pitfalls
- Polish
EPSG:2180orders axes North then East (850000, 100000): reading WMTS TopLeftCorner values as East-first withoutnorthEastProjections(or +axis=neu) misplaces every tile thousands of kilometres from Poland. - Always assign a valid
extentto customproj4projections—without one, OpenLayers guesses a huge global extent that makes initial zoom levels unusable on national grids.
Related examples
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.