Projections · Angular, React and OpenLayers
Equal Earth with a moving central meridian
Render world countries in a dynamic Equal Earth projection whose central meridian follows horizontal panning in 5-degree steps with antimeridian cuts.

What this example shows
World countries render in seven pastel colours inside the equal-area Equal Earth projection initially centred on Kraków’s 20° E meridian—keeping Europe and Africa upright and minimally sheared in the middle.
Panning east or west shifts the projection’s central meridian dynamically in 5-degree increments (recentre()) while slicing trans-antimeridian countries cleanly at the opposite side of the globe and highlighting hovered countries in white.
When you need it
Global thematic choropleths (carbon emissions, biodiversity, population density) require an equal-area projection so Greenland does not dwarf Africa, while allowing users to rotate the globe’s focal meridian to the Americas, Europe or Asia.
Updating +lon_0 dynamically gives an interactive globe-like experience on a flat 2D equal-area map.
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.
equal-earth-geojson.shared.tsimport type Feature from 'ol/Feature.js';
import type View from 'ol/View.js';
import type { Coordinate } from 'ol/coordinate.js';
import type { FeatureLoader } from 'ol/featureloader.js';
import GeoJSON from 'ol/format/GeoJSON.js';
import { createTransformFromCoordinateTransform, get as getProjection, toLonLat } from 'ol/proj.js';
import type Projection from 'ol/proj/Projection.js';
import type VectorSource from 'ol/source/Vector.js';
import type { FlatStyle } from 'ol/style/flat.js';
import { loadProj4, polygonsAroundMeridian, type Proj4, registerProjectionDefinitions } from 'cc-openlayers/core';
/** The countries file: Natural Earth polygons with a name and a map colour from 1 to 7. */
export interface Countries {
readonly type: 'FeatureCollection';
readonly features: {
readonly type: 'Feature';
readonly properties: { readonly name: string; readonly mapcolor: number };
readonly geometry:
| { readonly type: 'Polygon'; readonly coordinates: Coordinate[][] }
| { readonly type: 'MultiPolygon'; readonly coordinates: Coordinate[][][] };
}[];
}
/** What the example waits for before it draws: proj4 and the countries. */
export interface Loaded {
readonly proj4: Proj4;
readonly countries: Countries;
}
/** Loads proj4 and the countries file; rejects when the file cannot be read. */
export async function loadEqualEarthData(): Promise<Loaded> {
const [proj4, response] = await Promise.all([loadProj4(), fetch('assets/world/countries.geojson')]);
if (!response.ok) throw new Error(`assets/world/countries.geojson: ${response.status}`);
return { proj4, countries: (await response.json()) as Countries };
}
/** Seven colours no two neighbouring countries share, by the countries' `mapcolor` from 1 to 7. */
const COLOURS = ['#fbb4ae', '#b3cde3', '#ccebc5', '#decbe4', '#fed9a6', '#ffffcc', '#e5d8bd'];
/** The fill of a country by its map colour. */
export const COUNTRY_STYLE: FlatStyle = {
'fill-color': ['match', ['get', 'mapcolor'], ...COLOURS.flatMap((colour, index) => [index + 1, colour]), '#eee'],
};
/** The outline of the country under the pointer. */
export const HIGHLIGHT_STYLE: FlatStyle = { 'stroke-color': 'rgba(255, 255, 255, 0.7)', 'stroke-width': 2 };
/** Equal Earth around a central meridian, registered with proj4 the first time it is asked for. */
export function equalEarth(proj4: Proj4, meridian: number): Projection {
const code = `EqualEarth${meridian}`;
let projection = getProjection(code);
if (!projection) {
registerProjectionDefinitions(proj4, {
[code]: `+proj=eqearth +lon_0=${meridian} +x_0=0 +y_0=0 +R=6371008.7714 +units=m +no_defs +type=crs`,
});
projection = getProjection(code) as Projection;
projection.setGlobal(true);
projection.setExtent([-17243959.06, -8392927.6, 17243959.06, 8392927.6]);
projection.setWorldExtent([-180, -90, 180, 90]);
}
return projection;
}
/** Reads the countries, cut at the meridian's antimeridian, in the Equal Earth projection around that meridian. */
export function countriesLoader(proj4: Proj4, countries: Countries, meridian: number): FeatureLoader<Feature> {
// proj4 itself projects the countries: OpenLayers' transform from EPSG:4326 would move the longitudes beyond
// 180° that the cut leaves east of a meridian east of 0° by a whole world.
const project = createTransformFromCoordinateTransform(
proj4('EPSG:4326', equalEarth(proj4, meridian).getCode()).forward
);
return function (this: VectorSource, _extent, _resolution, _projection, success) {
const cut = {
...countries,
features: countries.features.map((country) => ({
...country,
geometry: {
type: 'MultiPolygon',
coordinates: polygonsAroundMeridian(
country.geometry.type === 'Polygon' ? [country.geometry.coordinates] : country.geometry.coordinates,
meridian
),
},
})),
};
const features = new GeoJSON().readFeatures(cut);
for (const feature of features) feature.getGeometry()?.applyTransform(project);
this.addFeatures(features);
success?.(features);
} as FeatureLoader<Feature>;
}
/** The multiple of 5° nearest the centre of the view: the central meridian the countries are cut around. */
export function nearestMeridian(view: View): number {
const [longitude] = toLonLat(view.getCenter() ?? [0, 0], view.getProjection());
return Math.round(longitude / 5) * 5;
}
/** Outlines `next` in the overlay in place of `previous`; returns the feature now outlined. */
export function swapHighlight(
overlay: VectorSource,
previous: Feature | undefined,
next: Feature | undefined
): Feature | undefined {
if (previous) overlay.removeFeature(previous);
if (next) overlay.addFeature(next);
return next;
}equal-earth-geojson.tsimport { ChangeDetectionStrategy, Component, computed, inject, PendingTasks, signal, viewChild } from '@angular/core';
import type Feature from 'ol/Feature';
import type MapBrowserEvent from 'ol/MapBrowserEvent';
import {
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
LayerVectorComponent,
MapComponent,
type Proj4,
SourceVectorComponent,
ViewComponent,
} from 'cc-openlayers';
import {
type Countries,
COUNTRY_STYLE,
countriesLoader,
equalEarth,
HIGHLIGHT_STYLE,
loadEqualEarthData,
nearestMeridian,
swapHighlight,
} from './equal-earth-geojson.shared';
/**
* The world's countries (Natural Earth) in the Equal Earth projection, whose central meridian follows the view:
* when the map is panned, the nearest multiple of 5° becomes the central meridian and the countries are cut at its
* antimeridian. The map starts with the whole world around Kraków's meridian; the country under the pointer is named
* and outlined.
*/
@Component({
selector: 'app-equal-earth-geojson',
imports: [
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
LayerVectorComponent,
MapComponent,
SourceVectorComponent,
ViewComponent,
],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
@if (ready()) {
<aol-map height="480px" (pointerMove)="move($event)" (olClick)="describe($event)">
<aol-interaction-default />
<aol-control-defaults />
<aol-view [projection]="projection()" [zoom]="1" [showFullExtent]="true" (changeCenter)="recentre()">
<aol-coordinate [x]="19.9373" [y]="0" srid="EPSG:4326" />
</aol-view>
<!-- A new projection gets new layers, whose features are read in it. -->
@for (projection of [projection()]; track projection.getCode()) {
<aol-layer-vector [extent]="projection.getExtent()" [style]="style">
<aol-source-vector
[loader]="loader()"
[overlaps]="false"
[wrapX]="false"
attributions="Countries: Natural Earth"
/>
</aol-layer-vector>
<aol-layer-vector [style]="highlightStyle">
<aol-source-vector #highlight />
</aol-layer-vector>
}
</aol-map>
<div class="example-controls">
<output>{{ name() }}</output>
</div>
}
`,
})
export class EqualEarthGeojson {
/** True once proj4 and the countries have loaded. */
readonly ready = signal(false);
readonly name = signal('');
/** The central meridian: Kraków's, rounded to a degree, until the map is panned. */
readonly meridian = signal(Math.round(19.9373));
protected readonly projection = computed(() => equalEarth(this.proj4 as Proj4, this.meridian()));
protected readonly loader = computed(() =>
countriesLoader(this.proj4 as Proj4, this.countries as Countries, this.meridian())
);
protected readonly style = COUNTRY_STYLE;
protected readonly highlightStyle = HIGHLIGHT_STYLE;
private readonly map = viewChild.required(MapComponent);
private readonly highlight = viewChild.required('highlight', { read: SourceVectorComponent });
private proj4?: Proj4;
private countries?: Countries;
private highlighted: Feature | undefined;
constructor() {
void inject(PendingTasks).run(async () => {
try {
const { proj4, countries } = await loadEqualEarthData();
this.proj4 = proj4;
this.countries = countries;
this.ready.set(true);
} catch (error) {
console.error('The countries could not be loaded', error);
}
});
}
/** Moves the central meridian to the multiple of 5° nearest the centre of the view. */
protected recentre(): void {
const meridian = nearestMeridian(this.map().instance.getView());
if (meridian === this.meridian()) return;
this.highlighted = undefined;
this.meridian.set(meridian);
}
protected move(event: MapBrowserEvent): void {
if (!event.dragging) this.describe(event);
}
protected describe(event: MapBrowserEvent): void {
const feature = this.map().instance.forEachFeatureAtPixel(event.pixel, (hit) => hit) as Feature | undefined;
this.name.set(feature?.get('name') ?? '');
if (feature === this.highlighted) return;
this.highlighted = swapHighlight(this.highlight().instance, this.highlighted, feature);
}
} 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.
equal-earth-geojson.react.tsximport { useEffect, useMemo, useRef, useState } from 'react';
import type Feature from 'ol/Feature.js';
import type OLMap from 'ol/Map.js';
import type MapBrowserEvent from 'ol/MapBrowserEvent.js';
import { fromLonLat } from 'ol/proj.js';
import type OLVectorSource from 'ol/source/Vector.js';
import { DefaultControls, DefaultInteractions, Map, VectorLayer, VectorSource, View } from 'cc-openlayers/react';
import {
COUNTRY_STYLE,
countriesLoader,
equalEarth,
HIGHLIGHT_STYLE,
type Loaded,
loadEqualEarthData,
nearestMeridian,
swapHighlight,
} from './equal-earth-geojson.shared';
/**
* The world's countries (Natural Earth) in the Equal Earth projection, whose central meridian follows the view:
* when the map is panned, the nearest multiple of 5° becomes the central meridian and the countries are cut at its
* antimeridian. The map starts with the whole world around Kraków's meridian; the country under the pointer is named
* and outlined.
*/
export function EqualEarthGeojson() {
/** Set once proj4 and the countries have loaded. */
const [loaded, setLoaded] = useState<Loaded>();
const [name, setName] = useState('');
/** The central meridian: Kraków's, rounded to a degree, until the map is panned. */
const [meridian, setMeridian] = useState(Math.round(19.9373));
const map = useRef<OLMap>(null);
const highlight = useRef<OLVectorSource>(null);
const highlighted = useRef<Feature>(undefined);
useEffect(() => {
let current = true;
void loadEqualEarthData().then(
(data) => {
if (current) setLoaded(data);
},
(error: unknown) => console.error('The countries could not be loaded', error)
);
return () => {
current = false;
};
}, []);
const projection = useMemo(() => loaded && equalEarth(loaded.proj4, meridian), [loaded, meridian]);
/**
* Kraków's longitude at the equator, in the projection of the first meridian. A coordinate declaration would put the
* view back there whenever the projection changes; the view itself carries its centre over to the new projection.
*/
const start = useMemo(
() => loaded && fromLonLat([19.9373, 0], equalEarth(loaded.proj4, Math.round(19.9373))),
[loaded]
);
const loader = useMemo(() => loaded && countriesLoader(loaded.proj4, loaded.countries, meridian), [loaded, meridian]);
/** Moves the central meridian to the multiple of 5° nearest the centre of the view. */
const recentre = () => {
const view = map.current?.getView();
if (!view) return;
const nearest = nearestMeridian(view);
if (nearest === meridian) return;
highlighted.current = undefined;
setMeridian(nearest);
};
const describe = (event: MapBrowserEvent) => {
const feature = map.current?.forEachFeatureAtPixel(event.pixel, (hit) => hit) as Feature | undefined;
setName(feature?.get('name') ?? '');
if (feature === highlighted.current) return;
const overlay = highlight.current;
if (!overlay) return;
highlighted.current = swapHighlight(overlay, highlighted.current, feature);
};
const move = (event: MapBrowserEvent) => {
if (!event.dragging) describe(event);
};
if (!projection || !loader || !start) return null;
return (
<>
<Map ref={map} height="480px" onPointerMove={move} onClick={describe}>
<DefaultInteractions />
<DefaultControls />
<View projection={projection} center={start} zoom={1} showFullExtent={true} onChangeCenter={recentre} />
{/* A new projection gets new layers, whose features are read in it. */}
<VectorLayer key={`countries-${projection.getCode()}`} extent={projection.getExtent()} style={COUNTRY_STYLE}>
<VectorSource loader={loader} overlaps={false} wrapX={false} attributions="Countries: Natural Earth" />
</VectorLayer>
<VectorLayer key={`highlight-${projection.getCode()}`} style={HIGHLIGHT_STYLE}>
<VectorSource ref={highlight} />
</VectorLayer>
</Map>
<div className="example-controls">
<output>{name}</output>
</div>
</>
);
}equal-earth-geojson.shared.tsimport type Feature from 'ol/Feature.js';
import type View from 'ol/View.js';
import type { Coordinate } from 'ol/coordinate.js';
import type { FeatureLoader } from 'ol/featureloader.js';
import GeoJSON from 'ol/format/GeoJSON.js';
import { createTransformFromCoordinateTransform, get as getProjection, toLonLat } from 'ol/proj.js';
import type Projection from 'ol/proj/Projection.js';
import type VectorSource from 'ol/source/Vector.js';
import type { FlatStyle } from 'ol/style/flat.js';
import { loadProj4, polygonsAroundMeridian, type Proj4, registerProjectionDefinitions } from 'cc-openlayers/core';
/** The countries file: Natural Earth polygons with a name and a map colour from 1 to 7. */
export interface Countries {
readonly type: 'FeatureCollection';
readonly features: {
readonly type: 'Feature';
readonly properties: { readonly name: string; readonly mapcolor: number };
readonly geometry:
| { readonly type: 'Polygon'; readonly coordinates: Coordinate[][] }
| { readonly type: 'MultiPolygon'; readonly coordinates: Coordinate[][][] };
}[];
}
/** What the example waits for before it draws: proj4 and the countries. */
export interface Loaded {
readonly proj4: Proj4;
readonly countries: Countries;
}
/** Loads proj4 and the countries file; rejects when the file cannot be read. */
export async function loadEqualEarthData(): Promise<Loaded> {
const [proj4, response] = await Promise.all([loadProj4(), fetch('assets/world/countries.geojson')]);
if (!response.ok) throw new Error(`assets/world/countries.geojson: ${response.status}`);
return { proj4, countries: (await response.json()) as Countries };
}
/** Seven colours no two neighbouring countries share, by the countries' `mapcolor` from 1 to 7. */
const COLOURS = ['#fbb4ae', '#b3cde3', '#ccebc5', '#decbe4', '#fed9a6', '#ffffcc', '#e5d8bd'];
/** The fill of a country by its map colour. */
export const COUNTRY_STYLE: FlatStyle = {
'fill-color': ['match', ['get', 'mapcolor'], ...COLOURS.flatMap((colour, index) => [index + 1, colour]), '#eee'],
};
/** The outline of the country under the pointer. */
export const HIGHLIGHT_STYLE: FlatStyle = { 'stroke-color': 'rgba(255, 255, 255, 0.7)', 'stroke-width': 2 };
/** Equal Earth around a central meridian, registered with proj4 the first time it is asked for. */
export function equalEarth(proj4: Proj4, meridian: number): Projection {
const code = `EqualEarth${meridian}`;
let projection = getProjection(code);
if (!projection) {
registerProjectionDefinitions(proj4, {
[code]: `+proj=eqearth +lon_0=${meridian} +x_0=0 +y_0=0 +R=6371008.7714 +units=m +no_defs +type=crs`,
});
projection = getProjection(code) as Projection;
projection.setGlobal(true);
projection.setExtent([-17243959.06, -8392927.6, 17243959.06, 8392927.6]);
projection.setWorldExtent([-180, -90, 180, 90]);
}
return projection;
}
/** Reads the countries, cut at the meridian's antimeridian, in the Equal Earth projection around that meridian. */
export function countriesLoader(proj4: Proj4, countries: Countries, meridian: number): FeatureLoader<Feature> {
// proj4 itself projects the countries: OpenLayers' transform from EPSG:4326 would move the longitudes beyond
// 180° that the cut leaves east of a meridian east of 0° by a whole world.
const project = createTransformFromCoordinateTransform(
proj4('EPSG:4326', equalEarth(proj4, meridian).getCode()).forward
);
return function (this: VectorSource, _extent, _resolution, _projection, success) {
const cut = {
...countries,
features: countries.features.map((country) => ({
...country,
geometry: {
type: 'MultiPolygon',
coordinates: polygonsAroundMeridian(
country.geometry.type === 'Polygon' ? [country.geometry.coordinates] : country.geometry.coordinates,
meridian
),
},
})),
};
const features = new GeoJSON().readFeatures(cut);
for (const feature of features) feature.getGeometry()?.applyTransform(project);
this.addFeatures(features);
success?.(features);
} as FeatureLoader<Feature>;
}
/** The multiple of 5° nearest the centre of the view: the central meridian the countries are cut around. */
export function nearestMeridian(view: View): number {
const [longitude] = toLonLat(view.getCenter() ?? [0, 0], view.getProjection());
return Math.round(longitude / 5) * 5;
}
/** Outlines `next` in the overlay in place of `previous`; returns the feature now outlined. */
export function swapHighlight(
overlay: VectorSource,
previous: Feature | undefined,
next: Feature | undefined
): Feature | undefined {
if (previous) overlay.removeFeature(previous);
if (next) overlay.addFeature(next);
return next;
}How the React version works
The world's countries in the Equal Earth projection around Kraków's meridian; panning moves the meridian to the nearest multiple of 5°, and the country under the pointer is named and outlined.
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 country styles, equalEarth, which registers the projection of a meridian, and countriesLoader, which cuts the countries at the antimeridian of the view, loadEqualEarthData, which loads proj4 and the countries and reports a failed load, nearestMeridian and swapHighlight from the example's .shared.ts file, so the logic exists once.
From Angular to React
| Angular | React |
|---|---|
PendingTasks.run loading proj4 and the countries, and @if (ready()) | a useEffect that loads both into useState; return null until they arrive |
computed projection and loader | useMemo |
<aol-coordinate> in the view | <View center={start}>, computed once: a Coordinate would move the view back whenever the projection changes |
@for (projection of [projection()]; track …), new layers per projection | <VectorLayer key={…projection.getCode()}> |
viewChild of the map and the highlight source, a field for the highlighted feature | useRef |
(changeCenter)="recentre()" | onChangeCenter={recentre} |
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. equalEarth registers each meridian's projection during render through useMemo, once per meridian.
Architecture and OpenLayers mechanics
Helper equalEarth registers +proj=eqearth +lon_0=${meridian} lazily via proj4 (starting at Math.round(19.9373) = 20° E), configuring projection extent, world extent and setGlobal(true). When panned, recentre() snaps to the nearest 5° meridian.
Because any country crossing meridian ± 180° would otherwise wrap straight across the entire map width, polygonsAroundMeridian clips rings along that dynamic antimeridian and projects vertices directly with proj4’s forward function inside @for over [projection()], while describe handles forEachFeatureAtPixel hover.
How it works
equalEarthregisters+proj=eqearth +lon_0=${meridian}on demand with extent, world extent andsetGlobal(true).- Starting at
Math.round(19.9373)(20° E),recentre()updates the active central meridian in 5° steps as the user pans. polygonsAroundMeridiansplits countries along the opposite antimeridian before projecting viaproj4forward.- Keying
@foron[projection()]rebuilds the vector layers in the new CRS, withdescribeoutlining hovered countries.
Pitfalls
- Whenever
+lon_0moves away from0°, geometries crossing lon_0 ± 180° must be split along that opposite meridian first—otherwise polygons spanning the cut line stretch horizontally across the entire map. proj4strings define coordinate math only—always callsetExtent,setWorldExtentandsetGlobal(true)on custom global projections so OpenLayers computes sensible zoom resolutions.
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.