Interactions · Angular, React and OpenLayers

Draw squares, boxes and stars

Draw oriented squares, axis-aligned boxes, circles and custom 12-vertex stars in OpenLayers using Circle Draw interactions, geometryFunction and Undo.

A map of Kraków with a circle drawn on the Main Square, a square turned over Wawel, a box over Kazimierz and a star north of the main station, with Star and Undo below.
A screenshot of the example. Map data © OpenStreetMap contributors.

What this example shows

Using two-click centre-and-radius gestures over Kraków, a shape selector lets you place circles on the Main Square, pointer-oriented rotated squares over Wawel, axis-aligned rectangles over Kazimierz, and custom six-pointed (12-vertex) stars north of the main station—paired with an Undo button that cancels an in-progress sketch.

When you need it

Site planners, emergency symbols and buffer tools frequently place parametric shapes—squares aligned with a street frontage, bounding boxes or custom star/hexagon markers—defined by a centre point and an outer radius click rather than clicking five or twelve individual corners.

OpenLayers’ geometryFunction hook lets a single two-click Circle interaction generate any mathematical polygon ring on the fly.

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-shapes.ts
import { ChangeDetectionStrategy, Component, computed, signal, viewChild } from '@angular/core';
import type { Coordinate } from 'ol/coordinate';
import type { SimpleGeometry } from 'ol/geom';
import Polygon from 'ol/geom/Polygon';
import { createBox, createRegularPolygon, type GeometryFunction } from 'ol/interaction/Draw';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerTileComponent,
  LayerVectorComponent,
  MapComponent,
  SourceOsmComponent,
  SourceVectorComponent,
  ViewComponent,
} from 'cc-openlayers';
import { DrawInteractionComponent } from 'cc-openlayers/editing';

type Shape = 'Circle' | 'Square' | 'Box' | 'Star' | 'None';

/** The shapes drawn with a `Circle` draw interaction whose geometry function makes a square, a box or a star. */
@Component({
  selector: 'app-draw-shapes',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    DrawInteractionComponent,
    LayerTileComponent,
    LayerVectorComponent,
    MapComponent,
    SourceOsmComponent,
    SourceVectorComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px">
      <aol-interaction-default />
      <aol-control-defaults />
      <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>
      <aol-layer-vector><aol-source-vector #source [wrapX]="false" /></aol-layer-vector>
      <!-- The draw interaction is made anew for each shape. -->
      @for (draw of drawings(); track draw.shape) {
        <aol-interaction-draw type="Circle" [geometryFunction]="draw.geometryFunction" [source]="source.instance" />
      }
    </aol-map>
    <div class="example-controls">
      <label>
        Shape type
        <select (change)="shape.set(value($event))">
          @for (option of shapes; track option) {
            <option [value]="option" [selected]="option === shape()">{{ option }}</option>
          }
        </select>
      </label>
      <button type="button" (click)="undo()">Undo</button>
    </div>
  `,
})
export class DrawShapes {
  readonly shape = signal<Shape>('Circle');
  protected readonly shapes: Shape[] = ['Circle', 'Square', 'Box', 'Star', 'None'];
  protected readonly drawings = computed(() => {
    const shape = this.shape();
    return shape === 'None' ? [] : [{ shape, geometryFunction: GEOMETRY_FUNCTIONS[shape] }];
  });
  private readonly draw = viewChild(DrawInteractionComponent);

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

  protected undo(): void {
    this.draw()?.instance.removeLastPoint();
  }
}

/** A star of twelve points around the centre; the last coordinate of the sketch sets its radius and rotation. */
export const starGeometry: GeometryFunction = (coordinates, geometry) => {
  const [center, last] = [(coordinates as Coordinate[])[0], (coordinates as Coordinate[]).at(-1) as Coordinate];
  const dx = center[0] - last[0];
  const dy = center[1] - last[1];
  const radius = Math.sqrt(dx * dx + dy * dy);
  const rotation = Math.atan2(dy, dx);
  const points = 12;
  const ring = Array.from({ length: points }, (_, index) => {
    const angle = rotation + (index * 2 * Math.PI) / points;
    const fraction = index % 2 === 0 ? 1 : 0.5;
    return [center[0] + radius * fraction * Math.cos(angle), center[1] + radius * fraction * Math.sin(angle)];
  });
  ring.push([...ring[0]]);
  const polygon = (geometry as Polygon | undefined) ?? new Polygon([ring]);
  polygon.setCoordinates([ring]);
  return polygon as SimpleGeometry;
};

/** The geometry function of each shape; a circle keeps the interaction's own. */
const GEOMETRY_FUNCTIONS: Record<Exclude<Shape, 'None'>, GeometryFunction | undefined> = {
  Circle: undefined,
  Square: createRegularPolygon(4),
  Box: createBox(),
  Star: starGeometry,
};

Architecture and OpenLayers mechanics

Every preset runs aol-interaction-draw with type="Circle" so click 1 fixes the centre coordinate and click 2 supplies the outer coordinate. Built-in helpers createRegularPolygon(4) and createBox() generate rotated squares and axis-aligned rectangles respectively, while custom starGeometry computes twelve alternating outer-radius and half-radius vertices oriented toward the pointer and closes the ring with ring.push.

Querying the interaction via viewChild lets the Undo button invoke removeLastPoint to abort an active two-click sketch before the second click commits it.

How it works

  • Three of the four tools share type="Circle" where the first click anchors the centre and the second sets radius and orientation, while createBox() treats the first click as one corner and the second as the opposite corner.
  • createRegularPolygon(4) builds a four-sided square rotated toward the cursor, while createBox() builds an axis-aligned rectangle between opposite corners.
  • starGeometry computes a custom 12-point alternating-radius polygon ring rotated toward the pointer.
  • Undo reaches the active Draw instance via viewChild and calls removeLastPoint to cancel an unfinished sketch.

Pitfalls

  • removeLastPoint affects only the uncommitted in-progress sketch—once the second click finishes a circle, box or star, removing it requires deleting the feature from the vector source (source.removeFeature(...)).
  • Custom polygon geometryFunction implementations must close every linear ring explicitly via ring.push(ring[0]) so exported GeoJSON and WKT geometries pass OGC validity checks.

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.