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.

The world's countries in seven pastel colours in the Equal Earth projection around 20° E, Africa and Europe in the middle, with Poland outlined in white under the pointer and named below the map.
A screenshot of the example. Countries: Natural Earth.

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

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

  • equalEarth registers +proj=eqearth +lon_0=${meridian} on demand with extent, world extent and setGlobal(true).
  • Starting at Math.round(19.9373) (20° E), recentre() updates the active central meridian in 5° steps as the user pans.
  • polygonsAroundMeridian splits countries along the opposite antimeridian before projecting via proj4 forward.
  • Keying @for on [projection()] rebuilds the vector layers in the new CRS, with describe outlining hovered countries.

Pitfalls

  • Whenever +lon_0 moves away from 0°, 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.
  • proj4 strings define coordinate math only—always call setExtent, setWorldExtent and setGlobal(true) on custom global projections so OpenLayers computes sensible zoom resolutions.

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.