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().

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.tsimport 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.tsimport { 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);
}
} 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.
geographic.react.tsximport { useEffect, useState } from 'react';
import type { Coordinate as OLCoordinate } from 'ol/coordinate.js';
import Point from 'ol/geom/Point.js';
import type MapBrowserEvent from 'ol/MapBrowserEvent.js';
import type MapEvent from 'ol/MapEvent.js';
import { clearUserProjection, useGeographic as setGeographicUserProjection } from 'ol/proj.js';
import {
CollectionCoordinates,
Coordinate,
DefaultControls,
DefaultInteractions,
Feature,
LineStringGeometry,
Map,
Overlay,
OSMSource,
PointGeometry,
PolygonGeometry,
TileLayer,
VectorLayer,
VectorSource,
View,
} from 'cc-openlayers/react';
import { CENTER, format, route, RYNEK, style, wawel } from './geographic.shared';
const OFFSET = [0, -12];
/**
* 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.
*/
export function Geographic() {
/** The coordinates of the popup, in longitude and latitude, while one is open. */
const [popup, setPopup] = useState<OLCoordinate | undefined>(undefined);
const [centre, setCentre] = useState<OLCoordinate>(CENTER);
// The view and the geometries read the user projection as they mount, before any passive effect runs; StrictMode
// clears it with the first effect's cleanup, so the effect sets it again.
useState(setGeographicUserProjection);
useEffect(() => {
setGeographicUserProjection();
return clearUserProjection;
}, []);
const moved = (event: MapEvent) => setCentre(event.map.getView().getCenter() ?? centre);
const hover = (event: MapBrowserEvent) => {
const { map } = event;
const viewport = map.getViewport();
if (viewport) viewport.style.cursor = map.hasFeatureAtPixel(event.pixel) ? 'pointer' : 'inherit';
};
const click = (event: MapBrowserEvent) => {
const geometry = event.map.getFeaturesAtPixel(event.pixel)[0]?.getGeometry();
if (!geometry) return setPopup(undefined);
// Under the geographic user projection, geometries and the click's coordinate are both in longitude and latitude.
setPopup(geometry instanceof Point ? geometry.getCoordinates() : event.coordinate);
};
return (
<>
<Map height="480px" onClick={click} onMoveEnd={moved} onPointerMove={hover}>
<DefaultInteractions />
<DefaultControls />
<View zoom={11} center={CENTER} />
<TileLayer>
<OSMSource />
</TileLayer>
<VectorLayer style={style}>
<VectorSource>
<Feature>
<PointGeometry>
<Coordinate x={RYNEK[0]} y={RYNEK[1]} srid="EPSG:4326" />
</PointGeometry>
</Feature>
<Feature>
<LineStringGeometry>
<CollectionCoordinates coordinates={route} srid="EPSG:4326" />
</LineStringGeometry>
</Feature>
<Feature>
<PolygonGeometry>
<CollectionCoordinates coordinates={wawel} srid="EPSG:4326" />
</PolygonGeometry>
</Feature>
</VectorSource>
</VectorLayer>
<Overlay positioning="bottom-center" offset={OFFSET} stopEvent={false} position={popup}>
{popup && (
<span className="example-label">
lon {format(popup[0])}, lat {format(popup[1])}
</span>
)}
</Overlay>
</Map>
<div className="example-controls">
<p className="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>
</>
);
}geographic.shared.tsimport 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);
}How the React version works
The view, the clicks and the features of Kraków given in longitude and latitude with useGeographic, while the map itself stays in Web Mercator: a point at the Main Square, a line to Wieliczka and a polygon around Wawel, a popup with the clicked position and readouts of the view centre.
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 coordinates of the Main Square, Wieliczka and Wawel, the centre of the view, the red style and format from the example's .shared.ts file, so the logic exists once.
From Angular to React
| Angular | React |
|---|---|
useGeographic() in the constructor and clearUserProjection on destroy | useState(setGeographicUserProjection) and a useEffect that sets it again and returns clearUserProjection |
signals of the popup position and the centre | useState |
(olClick), (moveEnd) and (pointerMove) with viewChild of the map | onClick, onMoveEnd and onPointerMove reading event.map, so no ref is needed |
viewChild of the overlay and setPosition | <Overlay position={popup}> |
@if (popup(); as position) around the label | {popup && …} |
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. useGeographic becomes setGeographicUserProjection, called in a useState initialiser, because the view and the geometries read the user projection while they mount, before any effect runs. StrictMode runs the effect's cleanup (clearUserProjection) once at the start, so the effect sets the projection again; the cleanup also restores it on unmount, as DestroyRef.onDestroy does in Angular.
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 viainject(DestroyRef).onDestroy(clearUserProjection). [center]="center"takes[19.9368, 50.0614]directly andgetCenter()reports settled view positions in degrees viamoved().- 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()andevent.coordinatedirectly in decimal degrees for popup display.
Pitfalls
useGeographic()mutates a module-global setting across the entire JavaScript bundle—forgettingclearUserProjectionon component destroy silently breaks sibling maps in your SPA that expect EPSG:3857 metres!- Because feature geometries now hold
EPSG:4326degree coordinates instead of Mercator metres, pass an explicit EPSG:4326 projection option whenever calling getLength or getArea from ol/sphere.
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.