Interactions · Angular, React and OpenLayers

Geodesic circles beside planar ones

Draw and edit true-scale geodesic circles in metres alongside planar Web Mercator circles in OpenLayers using spherical circular() polygons.

Central Europe around Poland with red geodesic circles of 150 km, larger over the Baltic than over Slovenia, and two equal green planar circles over Lithuania and Romania.
A screenshot of the example. Map data © OpenStreetMap contributors.

What this example shows

Whatever you draw as a geodesic circle keeps its true ground radius while changing apparent size with latitude—widening toward the north and shrinking toward the equator as Web Mercator stretches the map—whereas a planar projection circle keeps its screen size while its ground radius quietly changes.

Dragging any geodesic circle’s centre moves it across latitudes while recalculating its true ground shape live, and dragging its perimeter scales its geodesic radius in metres.

When you need it

Aviation range rings, telecom radio coverage zones, emergency evacuation radii and 100 km delivery catchments represent true distances on Earth’s curved surface rather than flat map pixels.

At Polish latitudes (50°–55° N), a naive Web Mercator Circle geometry distorts ground radius by 35–43%; representing range rings as spherical polygons preserves exact ground distances everywhere.

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.

draw-and-modify-geodesic.ts
import { ChangeDetectionStrategy, Component, computed, signal } from '@angular/core';
import type { FeatureLike } from 'ol/Feature';
import type Feature from 'ol/Feature';
import type { Coordinate } from 'ol/coordinate';
import GeometryCollection from 'ol/geom/GeometryCollection';
import Point from 'ol/geom/Point';
import Polygon, { circular } from 'ol/geom/Polygon';
import type { GeometryFunction } from 'ol/interaction/Draw';
import type SimpleGeometry from 'ol/geom/SimpleGeometry';
import Modify, { type ModifyEvent } from 'ol/interaction/Modify';
import { transform } from 'ol/proj';
import VectorSource from 'ol/source/Vector';
import { getDistance } from 'ol/sphere';
import CircleStyle from 'ol/style/Circle';
import Fill from 'ol/style/Fill';
import Stroke from 'ol/style/Stroke';
import Style, { type StyleFunction } from 'ol/style/Style';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerTileComponent,
  LayerVectorComponent,
  MapComponent,
  SourceOsmComponent,
  SourceVectorComponent,
  ViewComponent,
} from 'cc-openlayers';
import { DrawInteractionComponent, ModifyInteractionComponent, SnapInteractionComponent } from 'cc-openlayers/editing';

type DrawType = 'Point' | 'LineString' | 'Polygon' | 'Circle' | 'Geodesic';

const MAP_PROJECTION = 'EPSG:3857';

const style = new Style({
  fill: new Fill({ color: 'rgba(255, 255, 255, 0.2)' }),
  stroke: new Stroke({ color: '#33cc33', width: 2 }),
  image: new CircleStyle({ radius: 7, fill: new Fill({ color: '#ffcc33' }) }),
});

const geodesicStyle = new Style({
  // While a circle is edited, its changing geometry is shown, not the stored one.
  geometry: (feature) => (feature.get('modifyGeometry') as GeometryCollection | undefined) ?? feature.getGeometry(),
  fill: new Fill({ color: 'rgba(255, 255, 255, 0.2)' }),
  stroke: new Stroke({ color: '#ff3333', width: 2 }),
  image: new CircleStyle({ radius: 7, fill: new Fill({ color: 'rgba(0, 0, 0, 0)' }) }),
});

/** A geodesic circle of a centre and a radius in metres, as a polygon in the map projection. */
function geodesicPolygon(center: Coordinate, radius: number): Coordinate[][] {
  const circle = circular(transform(center, MAP_PROJECTION, 'EPSG:4326'), radius, 128);
  return circle.transform('EPSG:4326', MAP_PROJECTION).getCoordinates();
}

/** The radius in metres between two points of the map projection. */
function distance(from: Coordinate, to: Coordinate): number {
  return getDistance(transform(from, MAP_PROJECTION, 'EPSG:4326'), transform(to, MAP_PROJECTION, 'EPSG:4326'));
}

/** Draws a circle as a collection of a geodesic polygon and its centre point, which the modify interaction can drag. */
const geodesicGeometry: GeometryFunction = (coordinates, geometry) => {
  const [center, last] = coordinates as Coordinate[];
  const collection =
    (geometry as unknown as GeometryCollection | undefined) ??
    new GeometryCollection([new Polygon([]), new Point(center)]);
  const geometries = collection.getGeometries();
  (geometries[0] as Polygon).setCoordinates(geodesicPolygon(center, distance(center, last)));
  collection.setGeometries(geometries);
  // The draw interaction types its geometries as simple ones; a collection stands in for one here, as in OpenLayers' example.
  return collection as unknown as SimpleGeometry;
};

/** The style of the modify interaction's vertex, which also reshapes the circle being edited. */
function modifyStyle(): StyleFunction {
  const defaultStyle = new Modify({ source: new VectorSource() }).getOverlay().getStyleFunction() as StyleFunction;
  return (vertex, resolution) => {
    for (const feature of (vertex.get('features') ?? []) as Feature[]) {
      const modifyGeometry = feature.get('modifyGeometry') as GeometryCollection | undefined;
      if (modifyGeometry) reshape(modifyGeometry, (vertex.getGeometry() as Point).getCoordinates());
    }
    return defaultStyle(vertex, resolution);
  };
}

/** Moves the circle to the dragged centre, or gives it the radius to the dragged point. */
function reshape(modifyGeometry: GeometryCollection, dragged: Coordinate): void {
  const geometries = modifyGeometry.getGeometries();
  const polygon = (geometries[0] as Polygon).getCoordinates()[0];
  const center = (geometries[1] as Point).getCoordinates();
  const centerDragged = dragged[0] === center[0] && dragged[1] === center[1];
  // The centre keeps the radius, which is half the distance between two opposite vertices.
  const radius = centerDragged
    ? distance(polygon[0], polygon[(polygon.length - 1) / 2]) / 2
    : distance(center, dragged);
  (geometries[0] as Polygon).setCoordinates(geodesicPolygon(center, radius));
  modifyGeometry.setGeometries(geometries);
}

/** Circles drawn and edited as geodesic polygons, next to planar circles and the other geometry types. */
@Component({
  selector: 'app-draw-and-modify-geodesic',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    DrawInteractionComponent,
    LayerTileComponent,
    LayerVectorComponent,
    MapComponent,
    ModifyInteractionComponent,
    SnapInteractionComponent,
    SourceOsmComponent,
    SourceVectorComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px">
      <aol-interaction-default />
      <aol-control-defaults />
      <aol-view [zoom]="6">
        <aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" />
      </aol-view>
      <aol-layer-tile><aol-source-osm /></aol-layer-tile>
      <aol-layer-vector [style]="featureStyle"><aol-source-vector #source /></aol-layer-vector>
      <aol-interaction-modify
        [source]="source.instance"
        [style]="modifyStyle"
        (olModifyStart)="modifyStart($event)"
        (olModifyEnd)="modifyEnd($event)"
      />
      <!-- Draw and snap are made anew for each type; snap after draw, so it adjusts the pointer for it. -->
      @for (current of types; track current) {
        @if (current === type()) {
          <aol-interaction-draw
            [type]="drawType()"
            [source]="source.instance"
            [geometryFunction]="current === 'Geodesic' ? geodesicGeometry : undefined"
          />
          <aol-interaction-snap [source]="source.instance" />
        }
      }
    </aol-map>
    <div class="example-controls">
      <label>
        Geometry type
        <select (change)="type.set(value($event))">
          @for (option of types; track option) {
            <option [value]="option" [selected]="option === type()">{{ labels[option] }}</option>
          }
        </select>
      </label>
      <p class="example-hint">
        Move a geodesic and a planar circle between northern and southern latitudes to see how they differ.
      </p>
    </div>
  `,
})
export class DrawAndModifyGeodesic {
  readonly type = signal<DrawType>('Geodesic');
  protected readonly drawType = computed(() => {
    const type = this.type();
    return type === 'Geodesic' ? 'Circle' : type;
  });
  protected readonly types: DrawType[] = ['Point', 'LineString', 'Polygon', 'Circle', 'Geodesic'];
  protected readonly labels: Record<DrawType, string> = {
    Point: 'Point',
    LineString: 'LineString',
    Polygon: 'Polygon',
    Circle: 'Circle Geometry',
    Geodesic: 'Geodesic Circle',
  };
  protected readonly geodesicGeometry = geodesicGeometry;
  protected readonly modifyStyle = modifyStyle();

  protected featureStyle(feature: FeatureLike): Style {
    return feature.getGeometry()?.getType() === 'GeometryCollection' ? geodesicStyle : style;
  }

  /** A geodesic circle is edited on a copy, which the vertex style reshapes while the pointer drags. */
  protected modifyStart(event: ModifyEvent): void {
    for (const feature of event.features.getArray()) {
      const geometry = feature.getGeometry();
      if (geometry?.getType() === 'GeometryCollection') feature.set('modifyGeometry', geometry.clone(), true);
    }
  }

  /** The edited copy becomes the feature's geometry. */
  protected modifyEnd(event: ModifyEvent): void {
    for (const feature of event.features.getArray()) {
      const modifyGeometry = feature.get('modifyGeometry');
      if (modifyGeometry) {
        feature.setGeometry(modifyGeometry);
        feature.unset('modifyGeometry', true);
      }
    }
  }

  protected value(event: Event): DrawType {
    return (event.target as HTMLSelectElement).value as DrawType;
  }
}

Architecture and OpenLayers mechanics

In Geodesic Circle mode, Draw uses geometryFunction to build a two-part GeometryCollection: a 128-vertex spherical polygon generated by circular (from ol/geom/Polygon) paired with its geographic centre Point, measuring radii via spherical getDistance.

Storing both parts lets Modify drag the centre point to relocate the ring or drag perimeter vertices to resize its radius—updating a temporary clone in modifyGeometry rendered by modifyStyle during the drag and committing it on olModifyEnd, while Snap locks onto the ring vertices and edges as well as the centre point.

How it works

  • Geodesic drawing uses a geometryFunction producing a GeometryCollection of a 128-vertex circular polygon plus its centre point.
  • Rim vertices resize the ring through spherical getDistance; the centre child point is only repositioned, so treat the stored centre as the ring’s anchor while editing.
  • modifyStyle previews live changes inside modifyGeometry during drags before writing the final shape at olModifyEnd.
  • Planar Circle mode draws native Circle geometries whose Web Mercator map size stays constant while true ground radius shrinks northward.
  • Snap reads the whole collection, so it locks onto the ring vertices and edges as well as the centre point.

Pitfalls

  • OpenLayers’ native Circle class is strictly planar and GeoJSON defines no circle primitive at all—persist range rings either as [centerLonLat, radiusMeters] metadata or as the 128-vertex GeoJSON polygon produced by circular.
  • Never pass true ground metres directly as a Web Mercator Circle radius away from the equator: in Kraków, 100 projection units span only ~64 metres on the ground.

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.