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.

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.tsimport { 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' : '';
}
} The React version uses the library's React adapter, cc-openlayers/react: each component creates the OpenLayers object it names when it mounts, updates it from its props and disposes of it when it unmounts.
kml.react.tsximport { useRef, useState } from 'react';
import type OLMap from 'ol/Map.js';
import type MapBrowserEvent from 'ol/MapBrowserEvent.js';
import { getTopLeft, getWidth } from 'ol/extent.js';
import KML from 'ol/format/KML.js';
import { EXTENT } from 'ol/proj/epsg3857.js';
import {
Coordinate,
DefaultControls,
DefaultInteractions,
Map,
TileLayer,
VectorLayer,
VectorSource,
View,
WMTSSource,
useWMTSTileGrid,
} from 'cc-openlayers/react';
const size = getWidth(EXTENT) / 256;
const gridOptions = {
origin: getTopLeft(EXTENT),
resolutions: Array.from({ length: 20 }, (_, z) => size / 2 ** z),
matrixIds: Array.from({ length: 20 }, (_, z) => `EPSG:3857:${z}`),
};
const format = new KML();
/** 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. */
export function Kml() {
const [info, setInfo] = useState('–');
const map = useRef<OLMap>(null);
const tileGrid = useWMTSTileGrid(gridOptions);
const show = (event: MapBrowserEvent) => {
if (event.dragging) return;
const current = map.current;
if (!current) return;
const names: string[] = [];
current.forEachFeatureAtPixel(event.pixel, (feature) => {
names.push(feature.get('name'));
});
setInfo(names.length ? names.join(', ') || '(unknown)' : '–');
(current.getTargetElement() as HTMLElement).style.cursor = names.length ? 'pointer' : '';
};
return (
<>
<Map ref={map} height="480px" onPointerMove={show} onClick={show}>
<DefaultInteractions />
<DefaultControls />
<View zoom={12}>
<Coordinate x={19.977} y={50.029} srid="EPSG:4326" />
</View>
<TileLayer>
<WMTSSource
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}
tileGrid={tileGrid}
/>
</TileLayer>
<VectorLayer>
<VectorSource
url="assets/samples/sample-places.kml"
format={format}
attributions='River and meadow © <a href="https://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a> contributors'
/>
</VectorLayer>
</Map>
<div className="example-controls">
<span>
Feature <output>{info}</output>
</span>
</div>
</>
);
}How the React version works
Sample places in and around Kraków from a KML file (points, a polygon, a line) over the orthophoto, named under the pointer.
What both versions share
OpenLayers renders the map and handles the interactions; the cc-openlayers/core layer gives both adapters the same view binding (MapViewBinding) and the same conversion of coordinates from EPSG:4326 to the map's projection.
From Angular to React
| Angular | React |
|---|---|
<aol-layer-vector> with <aol-source-vector [url] [format]> | <VectorLayer> with <VectorSource url format>; the format is a module constant |
<aol-source-tilewmts> with <aol-tilegrid-wmts> | <WMTSSource> with a grid from useWMTSTileGrid |
(pointerMove) and viewChild of the map | onPointerMove (and onClick) on Map with useRef<OLMap>; the reading in useState |
Who creates, updates and disposes
Map creates the ol/Map in useLayoutEffect and disposes of it on unmount; each layer, source and interaction component adds its object to the parent it gets from context and removes it in its effect's cleanup, as ngOnDestroy does in Angular.
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.
forEachFeatureAtPixelcollects 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.
Related examples
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.