Styling and labels · Angular, React and OpenLayers

Stroke options of a line style

Test every OpenLayers Stroke option live—width, color, cap, join, miterLimit, dash pattern and lateral pixel offset—with draw, modify and snap.

OpenStreetMap around Kraków at zoom 9 with nine sample lines in wide blue dashes, each offset beside a thin grey dashed line where it really runs, and the form of stroke options below the map.
A screenshot of the example. Map data © OpenStreetMap contributors.

What this example shows

Around Kraków at zoom 9 over OpenStreetMap, nine multi-angle sample lines and any new polygons you sketch respond immediately to a comprehensive stroke-styling form controlling colour, width, line cap, line join, miter limit, dash array, dash offset and sideways pixel offset (accompanied by a thin grey dashed reference line showing true geometry position whenever offset is non-zero).

When you need it

Technical cartography relies heavily on advanced stroke parameters: lateral pixel offset separates parallel bus routes or dual-circuit power lines sharing one centreline, dash arrays mark planned vs existing pipes, and miterLimit prevents spiky acute road corners.

Experimenting with all Stroke properties simultaneously on sharp corners and drawn polygons reveals exact rendering behaviour before codifying enterprise SLD/cartographic standards.

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.

line-styles.ts
import { ChangeDetectionStrategy, Component, computed, signal } from '@angular/core';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerTileComponent,
  LayerVectorComponent,
  MapComponent,
  SourceGeoJSONComponent,
  SourceOsmComponent,
  ViewComponent,
} from 'cc-openlayers';
import { DrawInteractionComponent, ModifyInteractionComponent, SnapInteractionComponent } from 'cc-openlayers/editing';
import Stroke from 'ol/style/Stroke';
import Style from 'ol/style/Style';

/** Sample lines styled by a form of stroke options, editable with the draw, modify and snap interactions. */
@Component({
  selector: 'app-line-styles',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    DrawInteractionComponent,
    LayerTileComponent,
    LayerVectorComponent,
    MapComponent,
    ModifyInteractionComponent,
    SnapInteractionComponent,
    SourceGeoJSONComponent,
    SourceOsmComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px">
      <aol-interaction-default />
      <aol-control-defaults />
      <aol-view [zoom]="9">
        <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]="styles()">
        <aol-source-geojson #source url="assets/line-samples.geojson" featureProjection="EPSG:3857" />
      </aol-layer-vector>
      <aol-interaction-modify [source]="source.instance" />
      <aol-interaction-draw type="Polygon" [source]="source.instance" />
      <aol-interaction-snap [source]="source.instance" />
    </aol-map>
    <div class="example-controls">
      <label> Color <input id="color" type="color" [value]="color()" (change)="color.set(text($event))" /> </label>
      <span>
        Line Cap
        @for (cap of caps; track cap) {
          <label>
            <input type="radio" name="lineCap" [value]="cap" [checked]="lineCap() === cap" (click)="lineCap.set(cap)" />
            {{ cap }}
          </label>
        }
      </span>
      <span>
        Line Join
        @for (join of joins; track join) {
          <label>
            <input
              type="radio"
              name="lineJoin"
              [value]="join"
              [checked]="lineJoin() === join"
              (click)="lineJoin.set(join)"
            />
            {{ join }}
          </label>
        }
      </span>
      <label>
        Line Dash
        <input
          id="lineDash"
          type="text"
          placeholder="1, 3"
          [value]="lineDash()"
          (change)="lineDash.set(text($event))"
        />
      </label>
      <label>
        Line Dash Offset
        <input
          id="lineDashOffset"
          type="number"
          min="-200"
          max="20"
          [value]="lineDashOffset()"
          (change)="lineDashOffset.set(number($event))"
        />
      </label>
      <label>
        Miter Limit
        <input
          id="miterLimit"
          type="number"
          min="1"
          max="20"
          [value]="miterLimit()"
          (change)="miterLimit.set(number($event))"
        />
      </label>
      <label>
        Offset
        <input id="offset" type="number" min="-20" max="20" [value]="offset()" (change)="offset.set(number($event))" />
      </label>
      <label>
        Width
        <input id="width" type="number" min="1" max="40" [value]="width()" (change)="width.set(number($event))" />
      </label>
    </div>
  `,
})
export class LineStyles {
  protected readonly caps = ['butt', 'round', 'square'] as const;
  protected readonly joins = ['bevel', 'round', 'miter'] as const;
  protected readonly color = signal('#004D7D');
  protected readonly lineCap = signal<(typeof this.caps)[number]>('round');
  protected readonly lineJoin = signal<(typeof this.joins)[number]>('round');
  protected readonly lineDash = signal('');
  protected readonly lineDashOffset = signal(0);
  protected readonly miterLimit = signal(10);
  protected readonly offset = signal(0);
  protected readonly width = signal(2);

  /** The line's style and, while it is offset, a dashed grey copy of the line where it really is. */
  protected readonly styles = computed(() => {
    const dash = this.lineDash()
      .split(',')
      .filter((value) => value.trim() !== '')
      .map(Number);
    const styles = [
      new Style({
        stroke: new Stroke({
          color: this.color(),
          lineCap: this.lineCap(),
          lineJoin: this.lineJoin(),
          lineDash: dash.length > 0 ? dash : undefined,
          lineDashOffset: this.lineDashOffset(),
          miterLimit: this.miterLimit(),
          width: this.width(),
          offset: this.offset(),
        }),
      }),
    ];
    if (Math.abs(this.offset()) > 0) {
      styles.push(new Style({ stroke: new Stroke({ color: '#aaa', width: 1, lineDash: [3, 3] }) }));
    }
    return styles;
  });

  protected number(event: Event): number {
    return (event.target as HTMLInputElement).valueAsNumber;
  }

  protected text(event: Event): string {
    return (event.target as HTMLInputElement).value;
  }
}

Architecture and OpenLayers mechanics

Form controls feed a reactive computed signal that returns a fresh Style array bound to [style] on the vector layer—automatically including a secondary thin grey dashed reference stroke whenever lateral offset is non-zero so you can see how positive offsets shift strokes to the right of digitisation direction.

Draw, Modify and Snap interactions share the exact same vector source so newly sketched or dragged shapes inherit the active stroke configuration immediately.

How it works

  • A computed signal builds a fresh array of OpenLayers Style instances bound to [style] whenever any form field changes.
  • offset shifts the rendered stroke laterally in pixels (to the right of line direction for positive numbers) beside a grey dashed true-centreline guide.
  • Comma-separated Line Dash numbers define pixel dash/gap lengths (leaving the input empty restores a solid stroke).
  • Line Join and Miter Limit control whether acute vertices form sharp miters, round bends or clipped bevels.
  • Shared Draw, Modify and Snap interactions let you draw new snapped polygons and drag existing vertices under the live stroke style.

Pitfalls

  • Mutating an existing OpenLayers Stroke object in place via setters does not notify the layer to repaint—either return a new Style/array reference from a computed signal as done here, or call layer.changed() explicitly.
  • Lateral stroke offset is relative to vertex digitisation order: two adjoining road segments drawn in opposite directions will shift to opposite sides of the centreline under the same positive offset.

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.