Styling and labels · Angular, React and OpenLayers

Icon width and height in pixels

Size an OpenLayers SVG marker directly by pixel width and height bindings while preserving aspect ratio when either dimension is cleared in UI.

OpenStreetMap of Kraków's Old Town at zoom 15 with a blue pin on the Main Market Square, and below the map the width and height fields at 40 with the scale.
A screenshot of the example. Map data © OpenStreetMap contributors.

What this example shows

Over Kraków’s Old Town at zoom 15, a map pin on the Main Market Square is sized via two numeric form inputs (Width and Height, starting at 40 px) rather than an abstract scale multiplier, with the computed internal scale factor and effective rendered dimensions reported live below the map.

Setting both numbers stretches or squashes the pin to exact pixel dimensions, whereas clearing either field automatically scales the missing axis proportionally to preserve the SVG’s natural aspect ratio.

When you need it

UI design specs always prescribe marker sizes in CSS pixels (32 × 32 px or 40 px tall), even when underlying user-uploaded or library icons vary wildly in intrinsic SVG/PNG dimensions (24 px, 64 px, 512 px).

Specifying target width and height in pixels lets OpenLayers compute the exact scale factor automatically once each image loads.

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.

icon-width.ts
import { ChangeDetectionStrategy, Component, signal, viewChild } from '@angular/core';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  FeatureComponent,
  GeometryPointComponent,
  LayerTileComponent,
  LayerVectorComponent,
  MapComponent,
  SourceOsmComponent,
  SourceVectorComponent,
  StyleComponent,
  StyleIconComponent,
  ViewComponent,
} from 'cc-openlayers';

/** A marker whose icon width and height are typed in, or cleared so the icon keeps its proportions. */
@Component({
  selector: 'app-icon-width',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    FeatureComponent,
    GeometryPointComponent,
    LayerTileComponent,
    LayerVectorComponent,
    MapComponent,
    SourceOsmComponent,
    SourceVectorComponent,
    StyleComponent,
    StyleIconComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px" (renderComplete)="measure()">
      <aol-interaction-default />
      <aol-control-defaults />
      <aol-view [zoom]="15"><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>
          <aol-feature>
            <aol-geometry-point><aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" /></aol-geometry-point>
            <aol-style><aol-style-icon src="assets/marker.svg" [width]="width()" [height]="height()" /></aol-style>
          </aol-feature>
        </aol-source-vector>
      </aol-layer-vector>
    </aol-map>
    <div class="example-controls">
      <label>
        Width
        <input name="width" type="number" [value]="widthField()" (input)="setWidth(number($event))" />
      </label>
      <button type="button" (click)="width.set(undefined)">Clear width</button>
      <label>
        Height
        <input name="height" type="number" [value]="heightField()" (input)="setHeight(number($event))" />
      </label>
      <button type="button" (click)="height.set(undefined)">Clear height</button>
      <span>
        Scale approx. <output>{{ scale() }}</output>
      </span>
    </div>
  `,
})
export class IconWidth {
  /** The size given to the icon; a cleared one is left to the icon. */
  readonly width = signal<number | undefined>(40);
  readonly height = signal<number | undefined>(40);
  /** The sizes the fields show: the typed ones, or the icon's own once it has drawn without one. */
  readonly widthField = signal(40);
  readonly heightField = signal(40);
  readonly scale = signal('');
  private readonly icon = viewChild.required(StyleIconComponent);

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

  protected setWidth(width: number): void {
    this.width.set(width);
    this.widthField.set(width);
    this.height.set(this.heightField());
  }

  protected setHeight(height: number): void {
    this.height.set(height);
    this.heightField.set(height);
    this.width.set(this.widthField());
  }

  /** Reads the icon's scale and the size it drew a cleared dimension with. */
  protected measure(): void {
    const icon = this.icon().instance;
    const scale = icon.getScale();
    this.scale.set(Array.isArray(scale) ? `[${scale.map((value) => value.toFixed(2)).join(', ')}]` : String(scale));
    const width = icon.getWidth();
    const height = icon.getHeight();
    if (this.width() === undefined && width !== undefined) this.widthField.set(Math.round(width));
    if (this.height() === undefined && height !== undefined) this.heightField.set(Math.round(height));
  }
}

Architecture and OpenLayers mechanics

Binding [width] and [height] on aol-style-icon passes target pixel dimensions to OpenLayers’ Icon constructor, which divides them by the loaded asset’s intrinsic size (40 / 24 for a 24 px SVG). Supplying both produces a two-element [scaleX, scaleY] tuple; omitting one produces a uniform scalar scale.

Because OpenLayers evaluates width and height only at Icon construction time, aol-style-icon instantiates a fresh Icon whenever either input changes, and (renderComplete) reads back the resolved scale and dimensions once the image has painted.

How it works

  • [width] and [height] on aol-style-icon size the 24-pixel SVG at 40 pixels by computing an internal 40 / 24 scale after load.
  • Providing both dimensions scales X and Y independently; clearing either dimension switches to uniform proportional scaling.
  • aol-style-icon recreates the underlying OpenLayers Icon whenever width or height inputs change.
  • (renderComplete) reads the live computed scale and effective pixel size into the form after rendering.

Pitfalls

  • Never pass scale alongside width or height in OpenLayers Icon options—OpenLayers throws when scale is combined with width or height.
  • getWidth() and getHeight() return undefined until the asynchronous image decode finishes, so always read them after load or inside (renderComplete).

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.