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.

OpenStreetMap of Kraków's Old Town in the Polish 1992 grid, found by the code 2180, with the reprojection's triangles outlined in black, and the code field, the result (EPSG:2180) ETRF2000-PL / CS92 and the checkboxes below the map.
A screenshot of the example. Map data © OpenStreetMap contributors.

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.ts
import { 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.ts
import { 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;
  }
}

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) and https://epsg.io/${number}.json (name and bbox area of use).
  • registerProjectionDefinitions registers the CRS while applyTransform (8 stops per edge) projects the geographic bbox into the new grid’s extent.
  • Updating [projection]="projection()" switches the view and warps aol-source-osm live, falling back to FALLBACK (EPSG:3857) on invalid inputs.
  • Checkboxes toggle setRenderReprojectionEdges, OpenStreetMap’s aol-source-tiledebug grid and aol-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 zoom 11 jumps from ~76 m/px in global EPSG:3857 down to street-level ~1.5 m/px in national EPSG:2180.

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.