Vector data · Angular, React and OpenLayers

Places and their styles from KML

Display KML placemarks, polygons and lines with embedded styles in OpenLayers over Kraków’s orthophotomap and inspect overlapping features.

The national orthophoto of Kraków with yellow pushpins at named places, the Vistula in blue and the Błonia meadow in green, named below the map while under the pointer.
A screenshot of the example. Orthophotomap © GUGiK. Map data © OpenStreetMap contributors.

What this example shows

Over GUGiK’s aerial orthophotomap of Kraków, an imported KML document renders using its own embedded cartography: four named landmarks marked with classic yellow pushpins, the Błonia meadow shaded as a translucent green polygon, and the Vistula river traced as a 3-pixel blue line.

Hovering or clicking anywhere on the map lists the names of all features beneath the pointer—reporting both the landmark and the underlying polygon or river whenever features overlap.

When you need it

Field engineers, environmental consultants, drone planners and municipal teams routinely exchange site annotations exported directly from Google Earth or handheld GPS software as .kml files.

Preserving the author’s embedded KML colours, line weights and point labels lets users review external exports faithfully without writing custom style rules per file.

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.

kml.ts
import { ChangeDetectionStrategy, Component, signal, viewChild } from '@angular/core';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerTileComponent,
  LayerVectorComponent,
  MapComponent,
  SourceTileWMTSComponent,
  SourceVectorComponent,
  TileGridWMTSComponent,
  ViewComponent,
} from 'cc-openlayers';
import type MapBrowserEvent from 'ol/MapBrowserEvent';
import { getTopLeft, getWidth } from 'ol/extent';
import KML from 'ol/format/KML';
import { EXTENT } from 'ol/proj/epsg3857';

const size = getWidth(EXTENT) / 256;

/** A KML file with sample places in and around Kraków (points, a polygon and a line), over the national orthophoto; features are named on hover and click. */
@Component({
  selector: 'app-kml',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    LayerTileComponent,
    LayerVectorComponent,
    MapComponent,
    SourceTileWMTSComponent,
    SourceVectorComponent,
    TileGridWMTSComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px" (pointerMove)="show($event)" (olClick)="show($event)">
      <aol-interaction-default />
      <aol-control-defaults />
      <aol-view [zoom]="12"><aol-coordinate [x]="19.977" [y]="50.029" srid="EPSG:4326" /></aol-view>
      <aol-layer-tile>
        <aol-source-tilewmts
          attributions='Tiles © <a href="https://www.geoportal.gov.pl/" target="_blank">GUGiK</a>'
          url="https://mapy.geoportal.gov.pl/wss/service/PZGIK/ORTO/WMTS/StandardResolution"
          layer="ORTOFOTOMAPA"
          matrixSet="EPSG:3857"
          format="image/jpeg"
          projection="EPSG:3857"
          [style]="'default'"
          [wrapX]="true"
        >
          <aol-tilegrid-wmts [origin]="origin" [resolutions]="resolutions" [matrixIds]="matrixIds" />
        </aol-source-tilewmts>
      </aol-layer-tile>
      <aol-layer-vector>
        <aol-source-vector
          url="assets/samples/sample-places.kml"
          [format]="format"
          attributions='River and meadow © <a href="https://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a> contributors'
        />
      </aol-layer-vector>
    </aol-map>
    <div class="example-controls">
      <span>
        Feature <output>{{ info() }}</output>
      </span>
    </div>
  `,
})
export class Kml {
  readonly info = signal('–');
  protected readonly format = new KML();
  protected readonly origin = getTopLeft(EXTENT);
  protected readonly resolutions = Array.from({ length: 20 }, (_, z) => size / 2 ** z);
  protected readonly matrixIds = Array.from({ length: 20 }, (_, z) => `EPSG:3857:${z}`);
  private readonly map = viewChild.required(MapComponent);

  protected show(event: MapBrowserEvent): void {
    if (event.dragging) return;
    const map = this.map().instance;
    const names: string[] = [];
    map.forEachFeatureAtPixel(event.pixel, (feature) => {
      names.push(feature.get('name'));
    });
    this.info.set(names.length ? names.join(', ') || '(unknown)' : '–');
    map.getTargetElement().style.cursor = names.length ? 'pointer' : '';
  }
}

Architecture and OpenLayers mechanics

Instantiating new KML() with its default style extraction enabled parses embedded KML <Style> definitions onto each decoded feature and automatically labels point placemarks with their names. Unstyled KML points inherit the format’s fallback yellow pushpin icon, while forEachFeatureAtPixel gathers every intersecting feature at the pointer pixel rather than stopping at the topmost hit.

How it works

  • new KML() preserves default style extraction, applying embedded strokes, fills and point name labels automatically.
  • Point placemarks without custom KML icon styles receive KML’s default yellow pushpin marker.
  • Embedded styles paint Błonia with a green outline and semi-transparent fill and the Vistula with a 3-pixel blue stroke.
  • forEachFeatureAtPixel collects all features under the cursor on hover or tap so overlapping placemarks and polygons are listed together.

Pitfalls

  • KML hex colour strings use 8-digit aabbggrr (alpha, blue, green, red) order rather than CSS rrggbb—meaning ffff0000 represents opaque blue, not red.
  • OpenLayers’ default fallback KML pushpin loads from maps.google.com: in offline environments or under strict Content Security Policies (img-src), supply your own default style or disable style extraction so unstyled points remain 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.