Projections · Angular, React and OpenLayers

Longitude and latitude as map coordinates

Work in WGS84 longitude and latitude across view center, clicks and vector features on a Web Mercator map using OpenLayers useGeographic().

OpenStreetMap of Kraków and its surroundings with a red point on the Main Square, a red line from it to Wieliczka and a small square over Wawel, and the centre of the view below the map, longitude 19.9368 and latitude 50.0614.
A screenshot of the example. Map data © OpenStreetMap contributors.

What this example shows

Over crisp, undistorted Web Mercator OpenStreetMap tiles of Kraków, a point on the Main Square, a polyline to Wieliczka and a polygon over Wawel—alongside live view-centre readouts and click popups—all accept and return [longitude, latitude] decimal degrees directly without manual fromLonLat / toLonLat calls.

When you need it

Nearly every REST API, GeoJSON payload, browser Geolocation fix and user form speaks [lon, lat] degrees, while almost every fast web basemap renders in EPSG:3857 Web Mercator.

Enabling OpenLayers’ geographic user projection gives application code a 100% degree-based API surface while keeping tiles crisp and conformal in Web Mercator underneath.

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.

geographic.shared.ts
import type { Coordinate } from 'ol/coordinate.js';
import type { FlatStyle } from 'ol/style/flat.js';

/** The Main Market Square, in longitude and latitude. */
export const RYNEK: Coordinate = [19.9373, 50.0617];
/** Wieliczka, in longitude and latitude. */
export const WIELICZKA: Coordinate = [20.0645, 49.9871];

/** The centre the map starts at, in longitude and latitude. */
export const CENTER: Coordinate = [19.9368, 50.0614];

/** The line from the Main Market Square to Wieliczka. */
export const route = [RYNEK, WIELICZKA];

/** A square of 0.002° each way around Wawel Hill. */
export const wawel = [
  [
    [19.9334, 50.052],
    [19.9374, 50.052],
    [19.9374, 50.056],
    [19.9334, 50.056],
    [19.9334, 50.052],
  ],
];

/** The red look of the point, the line and the polygon. */
export const style: FlatStyle = {
  'circle-radius': 9,
  'circle-fill-color': '#ff0000',
  'stroke-color': '#ff0000',
  'stroke-width': 3,
  'fill-color': 'rgba(255, 0, 0, 0.2)',
};

/** A coordinate as the popup and the centre readout print it. */
export function format(value: number): string {
  return value.toFixed(4);
}
geographic.ts
import { ChangeDetectionStrategy, Component, DestroyRef, inject, signal, viewChild } from '@angular/core';
import {
  CollectionCoordinatesComponent,
  ContentComponent,
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  FeatureComponent,
  GeometryLinestringComponent,
  GeometryPointComponent,
  GeometryPolygonComponent,
  LayerTileComponent,
  LayerVectorComponent,
  MapComponent,
  OverlayComponent,
  SourceOsmComponent,
  SourceVectorComponent,
  ViewComponent,
} from 'cc-openlayers';
import type { Coordinate } from 'ol/coordinate';
import Point from 'ol/geom/Point';
import type MapBrowserEvent from 'ol/MapBrowserEvent';
import { clearUserProjection, useGeographic } from 'ol/proj';
import { CENTER, format, route, RYNEK, style, wawel } from './geographic.shared';

/**
 * Longitude and latitude as the map's coordinates: `useGeographic()` makes the view centre, the events and the
 * overlay position geographic while the map stays in Web Mercator. A click on a feature opens a popup with its
 * coordinates; the centre of the view is shown below the map.
 */
@Component({
  selector: 'app-geographic',
  imports: [
    CollectionCoordinatesComponent,
    ContentComponent,
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    FeatureComponent,
    GeometryLinestringComponent,
    GeometryPointComponent,
    GeometryPolygonComponent,
    LayerTileComponent,
    LayerVectorComponent,
    MapComponent,
    OverlayComponent,
    SourceOsmComponent,
    SourceVectorComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px" (olClick)="click($event)" (moveEnd)="moved()" (pointerMove)="hover($event)">
      <aol-interaction-default />
      <aol-control-defaults />
      <aol-view [zoom]="11" [center]="center" />
      <aol-layer-tile><aol-source-osm /></aol-layer-tile>
      <aol-layer-vector [style]="style">
        <aol-source-vector>
          <aol-feature>
            <aol-geometry-point><aol-coordinate [x]="rynek[0]" [y]="rynek[1]" srid="EPSG:4326" /></aol-geometry-point>
          </aol-feature>
          <aol-feature>
            <aol-geometry-linestring>
              <aol-collection-coordinates [coordinates]="route" srid="EPSG:4326" />
            </aol-geometry-linestring>
          </aol-feature>
          <aol-feature>
            <aol-geometry-polygon>
              <aol-collection-coordinates [coordinates]="wawel" srid="EPSG:4326" />
            </aol-geometry-polygon>
          </aol-feature>
        </aol-source-vector>
      </aol-layer-vector>
      <aol-overlay positioning="bottom-center" [offset]="[0, -12]" [stopEvent]="false">
        <aol-content>
          @if (popup(); as position) {
            <span class="example-label">lon {{ format(position[0]) }}, lat {{ format(position[1]) }}</span>
          }
        </aol-content>
      </aol-overlay>
    </aol-map>
    <div class="example-controls">
      <p class="example-hint">Click the point, the line or the polygon to see where it was hit.</p>
      <span>
        Centre lon <output>{{ format(centre()[0]) }}</output>
      </span>
      <span>
        Centre lat <output>{{ format(centre()[1]) }}</output>
      </span>
    </div>
  `,
})
export class Geographic {
  /** The coordinates of the popup, in longitude and latitude, while one is open. */
  readonly popup = signal<Coordinate | undefined>(undefined);
  readonly centre = signal<Coordinate>(CENTER);
  protected readonly center = CENTER;
  protected readonly rynek = RYNEK;
  protected readonly route = route;
  protected readonly wawel = wawel;
  protected readonly style = style;
  private readonly map = viewChild.required(MapComponent);
  private readonly overlay = viewChild.required(OverlayComponent);

  constructor() {
    useGeographic();
    inject(DestroyRef).onDestroy(clearUserProjection);
  }

  protected format(value: number): string {
    return format(value);
  }

  protected moved(): void {
    this.centre.set(this.map().instance.getView().getCenter() ?? this.centre());
  }

  protected hover(event: MapBrowserEvent): void {
    const map = this.map().instance;
    map.getViewport().style.cursor = map.hasFeatureAtPixel(event.pixel) ? 'pointer' : 'inherit';
  }

  protected click(event: MapBrowserEvent): void {
    const map = this.map().instance;
    const geometry = map.getFeaturesAtPixel(event.pixel)[0]?.getGeometry();
    if (!geometry) {
      this.overlay().instance.setPosition(undefined);
      this.popup.set(undefined);
      return;
    }
    // Under the geographic user projection, geometries and the click's coordinate are both in longitude and latitude.
    const position = geometry instanceof Point ? geometry.getCoordinates() : event.coordinate;
    this.overlay().instance.setPosition(position);
    this.popup.set(position);
  }
}

Architecture and OpenLayers mechanics

Calling useGeographic() in the component constructor sets OpenLayers’ global user projection to EPSG:4326, paired with inject(DestroyRef).onDestroy(clearUserProjection) so leaving the page restores default projected coordinates for other maps.

[center]="center" accepts [19.9368, 50.0614] directly, getCenter() inside moved() returns degrees, features declared with srid="EPSG:4326" retain degree coordinates in geometry.getCoordinates(), and map click events supply event.coordinate in degrees.

How it works

  • Constructor useGeographic() enables degree coordinates across the API, cleaned up on teardown via inject(DestroyRef).onDestroy(clearUserProjection).
  • [center]="center" takes [19.9368, 50.0614] directly and getCenter() reports settled view positions in degrees via moved().
  • Vector geometries (srid="EPSG:4326") store degree vertices in memory while OpenLayers projects them to Web Mercator on each render pass.
  • Click handlers read geometry.getCoordinates() and event.coordinate directly in decimal degrees for popup display.

Pitfalls

  • useGeographic() mutates a module-global setting across the entire JavaScript bundle—forgetting clearUserProjection on component destroy silently breaks sibling maps in your SPA that expect EPSG:3857 metres!
  • Because feature geometries now hold EPSG:4326 degree coordinates instead of Mercator metres, pass an explicit EPSG:4326 projection option whenever calling getLength or getArea from ol/sphere.

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.