Projections · Angular, React and OpenLayers
Reprojection to an EPSG code looked up online
Look up any EPSG code live from epsg.io, register its proj4 definition and area-of-use extent, and reproject OpenStreetMap in the browser.

What this example shows
Typing any valid 4-to-6-digit EPSG code (such as 2180 for Polish CS92 or 2178 for Polish CS2000 zone 7) queries epsg.io on the fly, displays the official CRS title, and immediately warps OpenStreetMap around Kraków into that coordinate system—complete with toggles for reprojection triangles, XYZ tile debug wireframes and a degree graticule.
When you need it
Universal GIS viewers, GeoPackage/Shapefile inspection tools and surveyor portals cannot bundle all 6,000+ EPSG registry definitions up front in JavaScript.
Fetching both the .proj4 string and the .json area-of-use bounding box on demand keeps initial bundle size tiny while supporting practically any regional CRS on Earth.
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-by-code.shared.tsimport { applyTransform } from 'ol/extent.js';
import { get as getProjection, getTransform, type TransformFunction } from 'ol/proj.js';
import type Projection from 'ol/proj/Projection.js';
import { loadProj4, registerProjectionDefinitions } from 'cc-openlayers/core';
/** The projection the map returns to when a code cannot be used. */
export const FALLBACK = 'EPSG:3857';
/** What epsg.io's JSON gives for a code besides its name: where on Earth the system is meant to be used. */
interface EpsgRecord {
name?: string;
bbox?: { west_longitude: number; south_latitude: number; east_longitude: number; north_latitude: number };
}
/**
* Numbers the searches: `begin()` returns a check that stays true only until the next search begins, so an answer
* that arrives after a newer search was started can be ignored.
*/
export function createSearchCounter(): { begin(): () => boolean } {
let latest = 0;
return {
begin: () => {
const mine = ++latest;
return () => mine === latest;
},
};
}
async function fetchText(url: string): Promise<string> {
const response = await fetch(url);
if (!response.ok) throw new Error(`${url}: ${response.status}`);
return response.text();
}
/**
* Registers the definition of the EPSG code with proj4, gives its projection the extent of its area of use and
* returns the system's name; rejects for text that is no code or a code epsg.io does not describe.
*/
export async function defineEpsgCode(code: string): Promise<string> {
const number = code.slice('EPSG:'.length);
if (!/^\d{4,6}$/.test(number)) throw new Error('Not an EPSG code');
const [definition, json] = await Promise.all([
fetchText(`https://epsg.io/${number}.proj4`),
fetchText(`https://epsg.io/${number}.json`),
]);
const { name, bbox } = JSON.parse(json) as EpsgRecord;
if (!name || !bbox) throw new Error('No name or area of use');
registerProjectionDefinitions(await loadProj4(), { [code]: definition.trim() });
const projection = getProjection(code) as Projection;
const { west_longitude: west, south_latitude: south, north_latitude: north } = bbox;
// An area of use across the antimeridian, such as the Pacific's, ends east of it: 360 degrees past its west.
const east = bbox.east_longitude < west ? bbox.east_longitude + 360 : bbox.east_longitude;
const worldExtent = [west, south, east, north];
projection.setWorldExtent(worldExtent);
projection.setExtent(
applyTransform(worldExtent, getTransform('EPSG:4326', projection) as TransformFunction, undefined, 8)
);
return name;
}reprojection-by-code.tsimport { ChangeDetectionStrategy, Component, inject, PendingTasks, signal, viewChild } from '@angular/core';
import { createXYZ } from 'ol/tilegrid';
import Stroke from 'ol/style/Stroke';
import {
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
LayerTileComponent,
MapComponent,
SourceOsmComponent,
SourceTileDebugComponent,
ViewComponent,
} from 'cc-openlayers';
import { GraticuleComponent } from 'cc-openlayers/graticule';
import { createSearchCounter, defineEpsgCode, FALLBACK } from './reprojection-by-code.shared';
/** OpenStreetMap reprojected on the client to the coordinate system of an EPSG code looked up on epsg.io. */
@Component({
selector: 'app-reprojection-by-code',
imports: [
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
GraticuleComponent,
LayerTileComponent,
MapComponent,
SourceOsmComponent,
SourceTileDebugComponent,
ViewComponent,
],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<aol-map height="480px">
<aol-interaction-default />
<aol-control-defaults />
<aol-view [zoom]="11" [projection]="projection()">
<aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" />
</aol-view>
<aol-layer-tile><aol-source-osm /></aol-layer-tile>
<aol-layer-tile [visible]="showTiles()">
<aol-source-tiledebug [tileGrid]="tileGrid" projection="EPSG:3857" />
</aol-layer-tile>
@if (showGraticule()) {
<aol-graticule [strokeStyle]="graticuleStroke" [showLabels]="true" />
}
</aol-map>
<div class="example-controls">
<label>
EPSG code
<input
type="text"
inputmode="numeric"
placeholder="2180, 2178, 3035, 27700 …"
[value]="code()"
(input)="code.set(text($event))"
/>
</label>
<button type="button" (click)="search()">Search</button>
<output>{{ result() }}</output>
</div>
<div class="example-controls">
<label>
<input type="checkbox" [checked]="renderEdges()" (change)="setRenderEdges(checked($event))" />
Render reprojection edges
</label>
<label>
<input type="checkbox" [checked]="showTiles()" (change)="showTiles.set(checked($event))" />
Show tile coordinates
</label>
<label>
<input type="checkbox" [checked]="showGraticule()" (change)="showGraticule.set(checked($event))" />
Show graticule
</label>
<p class="example-hint">
The original looks the system up by name in a keyed service; here the code is enough, and its definition and
validity area come from epsg.io.
</p>
</div>
`,
})
export class ReprojectionByCode {
readonly code = signal('2180');
readonly projection = signal(FALLBACK);
readonly result = signal('');
readonly renderEdges = signal(false);
readonly showTiles = signal(false);
readonly showGraticule = signal(false);
protected readonly tileGrid = createXYZ({ maxZoom: 19 });
protected readonly graticuleStroke = new Stroke({ color: 'rgba(255,120,0,0.9)', width: 2, lineDash: [0.5, 4] });
private readonly osm = viewChild.required(SourceOsmComponent);
private readonly pendingTasks = inject(PendingTasks);
private readonly searches = createSearchCounter();
/** Looks the code up, registers its definition and shows the map in it; an unusable code returns to EPSG:3857. */
protected search(): void {
void this.pendingTasks.run(async () => {
this.result.set('Searching ...');
const isLatest = this.searches.begin();
const code = `EPSG:${this.code().trim()}`;
try {
const name = await defineEpsgCode(code);
if (!isLatest()) return;
this.projection.set(code);
this.result.set(`(${code}) ${name}`);
} catch {
if (!isLatest()) return;
this.projection.set(FALLBACK);
this.result.set(`Nothing usable found, using ${FALLBACK}...`);
}
});
}
protected setRenderEdges(render: boolean): void {
this.renderEdges.set(render);
this.osm().instance.setRenderReprojectionEdges(render);
}
protected text(event: Event): string {
return (event.target as HTMLInputElement).value;
}
protected checked(event: Event): boolean {
return (event.target as HTMLInputElement).checked;
}
} 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-by-code.react.tsximport { useRef, useState } from 'react';
import { createXYZ } from 'ol/tilegrid.js';
import Stroke from 'ol/style/Stroke.js';
import {
Coordinate,
DefaultControls,
DefaultInteractions,
Map,
OSMSource,
TileDebugSource,
TileLayer,
View,
} from 'cc-openlayers/react';
import { Graticule } from 'cc-openlayers/react/graticule';
import { createSearchCounter, defineEpsgCode, FALLBACK } from './reprojection-by-code.shared';
const TILE_GRID = createXYZ({ maxZoom: 19 });
const GRATICULE_STROKE = new Stroke({ color: 'rgba(255,120,0,0.9)', width: 2, lineDash: [0.5, 4] });
/** OpenStreetMap reprojected on the client to the coordinate system of an EPSG code looked up on epsg.io. */
export function ReprojectionByCode() {
const [code, setCode] = useState('2180');
const [projection, setProjection] = useState(FALLBACK);
const [result, setResult] = useState('');
const [renderEdges, setRenderEdges] = useState(false);
const [showTiles, setShowTiles] = useState(false);
const [showGraticule, setShowGraticule] = useState(false);
const searches = useRef(createSearchCounter());
/** Looks the code up, registers its definition and shows the map in it; an unusable code returns to EPSG:3857. */
const search = async () => {
setResult('Searching ...');
const isLatest = searches.current.begin();
const epsg = `EPSG:${code.trim()}`;
try {
const name = await defineEpsgCode(epsg);
if (!isLatest()) return;
setProjection(epsg);
setResult(`(${epsg}) ${name}`);
} catch {
if (!isLatest()) return;
setProjection(FALLBACK);
setResult(`Nothing usable found, using ${FALLBACK}...`);
}
};
return (
<>
<Map height="480px">
<DefaultInteractions />
<DefaultControls />
<View zoom={11} projection={projection}>
<Coordinate x={19.9368} y={50.0614} srid="EPSG:4326" />
</View>
<TileLayer>
<OSMSource renderReprojectionEdges={renderEdges} />
</TileLayer>
<TileLayer visible={showTiles}>
<TileDebugSource tileGrid={TILE_GRID} projection="EPSG:3857" />
</TileLayer>
{showGraticule && <Graticule strokeStyle={GRATICULE_STROKE} showLabels={true} />}
</Map>
<div className="example-controls">
<label>
EPSG code
<input
type="text"
inputMode="numeric"
placeholder="2180, 2178, 3035, 27700 …"
value={code}
onChange={(event) => setCode(event.target.value)}
/>
</label>
<button type="button" onClick={() => void search()}>
Search
</button>
<output>{result}</output>
</div>
<div className="example-controls">
<label>
<input type="checkbox" checked={renderEdges} onChange={(event) => setRenderEdges(event.target.checked)} />
Render reprojection edges
</label>
<label>
<input type="checkbox" checked={showTiles} onChange={(event) => setShowTiles(event.target.checked)} />
Show tile coordinates
</label>
<label>
<input type="checkbox" checked={showGraticule} onChange={(event) => setShowGraticule(event.target.checked)} />
Show graticule
</label>
<p className="example-hint">
The original looks the system up by name in a keyed service; here the code is enough, and its definition and
validity area come from epsg.io.
</p>
</div>
</>
);
}reprojection-by-code.shared.tsimport { applyTransform } from 'ol/extent.js';
import { get as getProjection, getTransform, type TransformFunction } from 'ol/proj.js';
import type Projection from 'ol/proj/Projection.js';
import { loadProj4, registerProjectionDefinitions } from 'cc-openlayers/core';
/** The projection the map returns to when a code cannot be used. */
export const FALLBACK = 'EPSG:3857';
/** What epsg.io's JSON gives for a code besides its name: where on Earth the system is meant to be used. */
interface EpsgRecord {
name?: string;
bbox?: { west_longitude: number; south_latitude: number; east_longitude: number; north_latitude: number };
}
/**
* Numbers the searches: `begin()` returns a check that stays true only until the next search begins, so an answer
* that arrives after a newer search was started can be ignored.
*/
export function createSearchCounter(): { begin(): () => boolean } {
let latest = 0;
return {
begin: () => {
const mine = ++latest;
return () => mine === latest;
},
};
}
async function fetchText(url: string): Promise<string> {
const response = await fetch(url);
if (!response.ok) throw new Error(`${url}: ${response.status}`);
return response.text();
}
/**
* Registers the definition of the EPSG code with proj4, gives its projection the extent of its area of use and
* returns the system's name; rejects for text that is no code or a code epsg.io does not describe.
*/
export async function defineEpsgCode(code: string): Promise<string> {
const number = code.slice('EPSG:'.length);
if (!/^\d{4,6}$/.test(number)) throw new Error('Not an EPSG code');
const [definition, json] = await Promise.all([
fetchText(`https://epsg.io/${number}.proj4`),
fetchText(`https://epsg.io/${number}.json`),
]);
const { name, bbox } = JSON.parse(json) as EpsgRecord;
if (!name || !bbox) throw new Error('No name or area of use');
registerProjectionDefinitions(await loadProj4(), { [code]: definition.trim() });
const projection = getProjection(code) as Projection;
const { west_longitude: west, south_latitude: south, north_latitude: north } = bbox;
// An area of use across the antimeridian, such as the Pacific's, ends east of it: 360 degrees past its west.
const east = bbox.east_longitude < west ? bbox.east_longitude + 360 : bbox.east_longitude;
const worldExtent = [west, south, east, north];
projection.setWorldExtent(worldExtent);
projection.setExtent(
applyTransform(worldExtent, getTransform('EPSG:4326', projection) as TransformFunction, undefined, 8)
);
return name;
}How the React version works
An EPSG code typed in a field, its definition and area of use fetched from epsg.io, and OpenStreetMap reprojected in the browser into that system around Kraków, with tile coordinates, a graticule and 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 FALLBACK, createSearchCounter, which lets only the latest search apply its answer, and defineEpsgCode, which fetches the definition and the area of use, registers the projection and sets its extents, reading an area across the antimeridian as running east of it, from the example's .shared.ts file, so the logic exists once.
From Angular to React
| Angular | React |
|---|---|
signals of the code, the projection, the result and the options | useState |
search() inside PendingTasks.run | an async handler of the button |
viewChild of the OpenStreetMap source and setRenderReprojectionEdges | <OSMSource renderReprojectionEdges={renderEdges} /> |
@if (showGraticule()) | {showGraticule && <Graticule … />} |
<aol-layer-tile [visible]="showTiles()"> with a tile debug source | <TileLayer visible={showTiles}> with <TileDebugSource> |
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.
Architecture and OpenLayers mechanics
Submitting a code fetches https://epsg.io/${number}.proj4 and https://epsg.io/${number}.json in parallel. registerProjectionDefinitions registers the proj4 string, sets the geographic bbox as the world extent, densifies each box edge with 8 stops via applyTransform to compute the projected extent, and updates [projection]="projection()" (falling back safely to FALLBACK, EPSG:3857, on invalid or unknown codes).
Diagnostic checkboxes toggle setRenderReprojectionEdges, aol-source-tiledebug and aol-graticule.
How it works
- Parallel requests fetch
https://epsg.io/${number}.proj4(transform math) andhttps://epsg.io/${number}.json(name andbboxarea of use). registerProjectionDefinitionsregisters the CRS whileapplyTransform(8 stops per edge) projects the geographicbboxinto the new grid’sextent.- Updating
[projection]="projection()"switches the view and warpsaol-source-osmlive, falling back toFALLBACK(EPSG:3857) on invalid inputs. - Checkboxes toggle
setRenderReprojectionEdges, OpenStreetMap’saol-source-tiledebuggrid andaol-graticule.
Pitfalls
- Areas of use crossing the 180° antimeridian (such as EPSG:3832, 98.69° E to 68° W) report west > east: add 360° to the eastern longitude before
applyTransform, otherwise the box wraps the wrong way around the globe. - Because zoom 0 of a newly registered projection spans its own area-of-use
extent, keeping zoom11jumps from ~76 m/px in globalEPSG:3857down to street-level ~1.5 m/px in national EPSG:2180.
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.