Interactions · Angular, React and OpenLayers

Draw a rectangle and read its GeoJSON

Draw a two-click bounding rectangle on an OpenLayers map using createBox() and export a cloned geometry as WGS84 GeoJSON in Angular and React.

A map of Kraków with a drawn rectangle over the city centre, the Draw button below it and the rectangle's GeoJSON.
A screenshot of the example. Map data © OpenStreetMap contributors.

What this example shows

Toggling the Draw button activates rectangle sketching over Kraków: clicking once sets the first corner, moving the pointer previews the expanding box, and clicking a second time completes the rectangle, renders it on a dedicated vector layer, and prints its geographic EPSG:4326 GeoJSON document below the map.

When you need it

Area-of-interest selectors, data-export clippers, report order forms and spatial search filters start by letting the user drag or click a clean rectangular box on the map and serialising that box as standard WGS84 GeoJSON for backend APIs.

Cloning the drawn Web Mercator geometry before transforming to EPSG:4326 preserves the on-map shape while giving forms clean degree coordinates.

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-polygon.ts
import { JsonPipe } from '@angular/common';
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import type { Feature as GeoJsonFeature, Polygon as GeoJsonPolygon } from 'geojson';
import Polygon from 'ol/geom/Polygon';
import { createBox, type DrawEvent } from 'ol/interaction/Draw';
import {
  CollectionCoordinatesComponent,
  CoordinateComponent,
  DefaultInteractionComponent,
  FeatureComponent,
  GeometryPolygonComponent,
  LayerTileComponent,
  LayerVectorComponent,
  MapComponent,
  SourceOsmComponent,
  SourceVectorComponent,
  ViewComponent,
} from 'cc-openlayers';
import { DrawInteractionComponent } from 'cc-openlayers/editing';

/** A rectangle drawn with the draw interaction and shown as geographic GeoJSON. */
@Component({
  selector: 'app-draw-polygon',
  imports: [
    CollectionCoordinatesComponent,
    CoordinateComponent,
    DefaultInteractionComponent,
    DrawInteractionComponent,
    FeatureComponent,
    GeometryPolygonComponent,
    JsonPipe,
    LayerTileComponent,
    LayerVectorComponent,
    MapComponent,
    SourceOsmComponent,
    SourceVectorComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px">
      <aol-interaction-default />
      @if (drawing()) {
        <aol-interaction-draw type="Circle" [geometryFunction]="box" (drawEnd)="drawEnd($event)" />
      }
      <aol-view [zoom]="13">
        <aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" />
      </aol-view>
      <aol-layer-tile><aol-source-osm /></aol-layer-tile>
      @if (drawn(); as drawn) {
        <aol-layer-vector>
          <aol-source-vector>
            <aol-feature>
              <aol-geometry-polygon>
                <aol-collection-coordinates [coordinates]="drawn.geometry.coordinates" srid="EPSG:4326" />
              </aol-geometry-polygon>
            </aol-feature>
          </aol-source-vector>
        </aol-layer-vector>
      }
    </aol-map>
    <div class="example-controls">
      <button type="button" [attr.aria-pressed]="drawing()" (click)="drawing.set(!drawing())">Draw</button>
    </div>
    @if (drawn(); as drawn) {
      <pre>{{ drawn | json }}</pre>
    }
  `,
})
export class DrawPolygon {
  readonly drawing = signal(false);
  readonly drawn = signal<GeoJsonFeature<GeoJsonPolygon> | undefined>(undefined);
  protected readonly box = createBox();

  protected drawEnd(event: DrawEvent): void {
    // A box: the draw interaction's geometry function makes a polygon. A clone keeps it in map coordinates.
    const geometry = event.feature.getGeometry() as Polygon;
    const geographic = geometry.clone().transform('EPSG:3857', 'EPSG:4326');
    this.drawn.set({
      type: 'Feature',
      properties: {},
      geometry: { type: 'Polygon', coordinates: geographic.getCoordinates() },
    });
  }
}

Architecture and OpenLayers mechanics

A boolean signal controls @if around aol-interaction-draw, configured with type="Circle" and OpenLayers’ createBox() geometryFunction so two clicks produce an axis-aligned rectangular Polygon.

In the drawEnd handler, the component clones the sketch geometry, transforms the clone from EPSG:3857 to EPSG:4326 for GeoJSON serialisation (displayed via Angular’s json pipe), and stores those WGS84 coordinates in state, from which the vector layer reprojects and renders the feature.

How it works

  • Toggling the Draw button mounts or removes aol-interaction-draw cleanly via @if.
  • Pairing type="Circle" with createBox() as geometryFunction turns a two-click centre/radius gesture into a corner-to-corner rectangle.
  • On drawEnd, transforming a clone() of the geometry into EPSG:4326 leaves the on-map feature safely in Web Mercator.
  • Reactive state feeds both the persistent vector feature on the map and the formatted GeoJSON readout via the json pipe.

Pitfalls

  • Never call .transform('EPSG:3857', 'EPSG:4326') directly on the live feature geometry attached to a Web Mercator layer—mutating it in place shrinks and teleports the drawn rectangle to 0°, 0°; always .clone() first.
  • OpenLayers’ Draw interaction discards its temporary sketch overlay as soon as drawEnd finishes—bind a target vector source or copy the finished feature into component state so the shape stays visible.

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.