Vector data · Angular, React and OpenLayers
OpenStreetMap data from the Overpass API
Query live OpenStreetMap buildings, streets, car parks and parks from the Overpass API by map extent in OpenLayers and style features by tag.

What this example shows
Zoomed closely onto Kraków’s Main Square at zoom 17 over Esri satellite imagery, raw OpenStreetMap vector geometries fetched live from the Overpass API render with tag-driven styles: building footprints in coral on top, street centrelines in white, car parks in grey, and trees and green squares in green.
When you need it
Urban analysis tools, solar-roof estimators, pedestrian accessibility audits and digital twins often need actual OpenStreetMap building polygons and tag metadata rather than pre-rendered PNG tiles.
Querying the Overpass API for a tight street-level bounding box pulls live OSM nodes, ways and relations straight into an OpenLayers vector source with zero custom backend database.
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.
vector-osm.tsimport { ChangeDetectionStrategy, Component } from '@angular/core';
import type Feature from 'ol/Feature';
import type { FeatureLike } from 'ol/Feature';
import type { Extent } from 'ol/extent';
import OSMXML from 'ol/format/OSMXML';
import { bbox } from 'ol/loadingstrategy';
import { transformExtent } from 'ol/proj';
import type Projection from 'ol/proj/Projection';
import type VectorSource from 'ol/source/Vector';
import CircleStyle from 'ol/style/Circle';
import Fill from 'ol/style/Fill';
import Stroke from 'ol/style/Stroke';
import Style from 'ol/style/Style';
import {
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
LayerTileComponent,
LayerVectorComponent,
MapComponent,
SourceImageTileComponent,
SourceVectorComponent,
ViewComponent,
} from 'cc-openlayers';
const OVERPASS = 'https://overpass-api.de/api/interpreter';
/** The style of a feature by the first of its tags that has one, by the tag's value (a regular expression). */
const STYLES: Record<string, Record<string, Style>> = {
amenity: {
parking: new Style({
stroke: new Stroke({ color: 'rgba(170, 170, 170, 1.0)', width: 1 }),
fill: new Fill({ color: 'rgba(170, 170, 170, 0.3)' }),
}),
},
building: {
'.*': new Style({
zIndex: 100,
stroke: new Stroke({ color: 'rgba(246, 99, 79, 1.0)', width: 1 }),
fill: new Fill({ color: 'rgba(246, 99, 79, 0.3)' }),
}),
},
highway: {
service: new Style({ stroke: new Stroke({ color: 'rgba(255, 255, 255, 1.0)', width: 2 }) }),
'.*': new Style({ stroke: new Stroke({ color: 'rgba(255, 255, 255, 1.0)', width: 3 }) }),
},
landuse: {
'forest|grass|allotments': new Style({
stroke: new Stroke({ color: 'rgba(140, 208, 95, 1.0)', width: 1 }),
fill: new Fill({ color: 'rgba(140, 208, 95, 0.3)' }),
}),
},
natural: {
tree: new Style({ image: new CircleStyle({ radius: 2, fill: new Fill({ color: 'rgba(140, 208, 95, 1.0)' }) }) }),
},
};
function osmStyle(feature: FeatureLike): Style | undefined {
for (const key in STYLES) {
const value = feature.get(key);
if (value === undefined) continue;
for (const pattern in STYLES[key]) {
if (new RegExp(pattern).test(value)) return STYLES[key][pattern];
}
}
return undefined;
}
/** Asks the Overpass API for the OpenStreetMap data within the extent to load and adds it to the source. */
function overpass(
this: VectorSource,
extent: Extent,
_resolution: number,
projection: Projection,
success?: (features: Feature[]) => void,
failure?: () => void
): void {
const [west, south, east, north] = transformExtent(extent, projection, 'EPSG:4326');
const client = new XMLHttpRequest();
client.open('POST', OVERPASS);
client.addEventListener('load', () => {
// A busy server answers 504 with an HTML page, and too many requests 429: failures, not data.
if (client.status !== 200) {
failure?.();
return;
}
const features = new OSMXML().readFeatures(client.responseText, { featureProjection: projection });
this.addFeatures(features);
success?.(features);
});
client.addEventListener('error', () => failure?.());
client.send(
`(node(${south},${Math.max(west, -180)},${north},${Math.min(east, 180)});` +
'rel(bn)->.foo;way(bn);node(w)->.foo;rel(bw););out meta;'
);
}
/**
* OpenStreetMap data around Kraków's Main Square, loaded as OSM XML from the Overpass API for each extent the map
* shows (a bbox strategy) and styled by its tags over Esri's World Imagery. Panning and zooming for long will
* eventually lead to "Too many requests" from the Overpass API.
*/
@Component({
selector: 'app-vector-osm',
imports: [
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
LayerTileComponent,
LayerVectorComponent,
MapComponent,
SourceImageTileComponent,
SourceVectorComponent,
ViewComponent,
],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<aol-map height="480px">
<aol-interaction-default />
<aol-control-defaults />
<aol-view [zoom]="17" [maxZoom]="19">
<aol-coordinate [x]="19.9373" [y]="50.0617" srid="EPSG:4326" />
</aol-view>
<aol-layer-tile>
<aol-source-imagetile
url="https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"
[maxZoom]="19"
attributions="Tiles © Esri — Source: Esri, Maxar, Earthstar Geographics, and the GIS User Community"
/>
</aol-layer-tile>
<aol-layer-vector [style]="style">
<aol-source-vector
[loader]="loader"
[strategy]="strategy"
attributions='© <a href="https://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a> contributors'
/>
</aol-layer-vector>
</aol-map>
`,
})
export class VectorOsm {
protected readonly loader = overpass;
protected readonly strategy = bbox;
protected readonly style = osmStyle;
} 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.
vector-osm.react.tsximport type Feature from 'ol/Feature.js';
import type { FeatureLike } from 'ol/Feature.js';
import type { Extent } from 'ol/extent.js';
import OSMXML from 'ol/format/OSMXML.js';
import { bbox } from 'ol/loadingstrategy.js';
import { transformExtent } from 'ol/proj.js';
import type Projection from 'ol/proj/Projection.js';
import type VectorSourceOL from 'ol/source/Vector.js';
import CircleStyle from 'ol/style/Circle.js';
import Fill from 'ol/style/Fill.js';
import Stroke from 'ol/style/Stroke.js';
import Style from 'ol/style/Style.js';
import {
Coordinate,
DefaultControls,
DefaultInteractions,
ImageTileSource,
Map,
TileLayer,
VectorLayer,
VectorSource,
View,
} from 'cc-openlayers/react';
const OVERPASS = 'https://overpass-api.de/api/interpreter';
/** The style of a feature by the first of its tags that has one, by the tag's value (a regular expression). */
const STYLES: Record<string, Record<string, Style>> = {
amenity: {
parking: new Style({
stroke: new Stroke({ color: 'rgba(170, 170, 170, 1.0)', width: 1 }),
fill: new Fill({ color: 'rgba(170, 170, 170, 0.3)' }),
}),
},
building: {
'.*': new Style({
zIndex: 100,
stroke: new Stroke({ color: 'rgba(246, 99, 79, 1.0)', width: 1 }),
fill: new Fill({ color: 'rgba(246, 99, 79, 0.3)' }),
}),
},
highway: {
service: new Style({ stroke: new Stroke({ color: 'rgba(255, 255, 255, 1.0)', width: 2 }) }),
'.*': new Style({ stroke: new Stroke({ color: 'rgba(255, 255, 255, 1.0)', width: 3 }) }),
},
landuse: {
'forest|grass|allotments': new Style({
stroke: new Stroke({ color: 'rgba(140, 208, 95, 1.0)', width: 1 }),
fill: new Fill({ color: 'rgba(140, 208, 95, 0.3)' }),
}),
},
natural: {
tree: new Style({ image: new CircleStyle({ radius: 2, fill: new Fill({ color: 'rgba(140, 208, 95, 1.0)' }) }) }),
},
};
function osmStyle(feature: FeatureLike): Style | undefined {
for (const key in STYLES) {
const value = feature.get(key);
if (value === undefined) continue;
for (const pattern in STYLES[key]) {
if (new RegExp(pattern).test(value)) return STYLES[key][pattern];
}
}
return undefined;
}
/** Asks the Overpass API for the OpenStreetMap data within the extent to load and adds it to the source. */
function overpass(
this: VectorSourceOL,
extent: Extent,
_resolution: number,
projection: Projection,
success?: (features: Feature[]) => void,
failure?: () => void
): void {
const [west, south, east, north] = transformExtent(extent, projection, 'EPSG:4326');
const client = new XMLHttpRequest();
client.open('POST', OVERPASS);
client.addEventListener('load', () => {
// A busy server answers 504 with an HTML page, and too many requests 429: failures, not data.
if (client.status !== 200) {
failure?.();
return;
}
const features = new OSMXML().readFeatures(client.responseText, { featureProjection: projection });
this.addFeatures(features);
success?.(features);
});
client.addEventListener('error', () => failure?.());
client.send(
`(node(${south},${Math.max(west, -180)},${north},${Math.min(east, 180)});` +
'rel(bn)->.foo;way(bn);node(w)->.foo;rel(bw););out meta;'
);
}
/**
* OpenStreetMap data around Kraków's Main Square, loaded as OSM XML from the Overpass API for each extent the map
* shows (a bbox strategy) and styled by its tags over Esri's World Imagery. Panning and zooming for long will
* eventually lead to "Too many requests" from the Overpass API.
*/
export function VectorOsm() {
return (
<Map height="480px">
<DefaultInteractions />
<DefaultControls />
<View zoom={17} maxZoom={19}>
<Coordinate x={19.9373} y={50.0617} srid="EPSG:4326" />
</View>
<TileLayer>
<ImageTileSource
url="https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"
maxZoom={19}
attributions="Tiles © Esri — Source: Esri, Maxar, Earthstar Geographics, and the GIS User Community"
/>
</TileLayer>
<VectorLayer style={osmStyle}>
<VectorSource
loader={overpass}
strategy={bbox}
attributions='© <a href="https://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a> contributors'
/>
</VectorLayer>
</Map>
);
}How the React version works
Parking, buildings, roads, green land and trees around the Main Square fetched from the Overpass API for each loaded extent and styled by their tags.
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 |
|---|---|
a source loader with the bbox strategy | <VectorSource loader strategy> with module constants |
the layer's [style] | the layer's style: a function or a flat style, constant in the module |
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
Driven by the bbox strategy, a custom vector loader posts an Overpass QL query selecting nodes and ways inside the visible box plus the relations containing those ways (out meta) and parses the response with OpenLayers’ OSMXML format.
The layer’s style function matches each feature’s OSM tags against ordered rules in STYLES—drawing buildings on top via zIndex: 100 above streets, parking areas and greenery—while treating non-200 HTTP responses (such as 429 rate limits or 504 gateway timeouts) as load failures.
How it works
- The custom loader posts an Overpass bounding-box query (
out meta) and decodes nodes, ways and polygons throughOSMXML. - Using the
bboxloading strategy fetches new street blocks incrementally as the user pans around the Old Town. - Ordered tag patterns in
STYLEScolour buildings coral (zIndex: 100), streets white, car parks grey and green spaces green. - HTTP responses other than 200 (including busy-server 504 or rate-limit 429 statuses) register cleanly as failed loads.
Pitfalls
- Failed extents remain recorded as loaded inside VectorSource—remove the failed box from the source’s loaded extents before attempting a programmatic retry.
- Never run raw Overpass queries unconstrained at city or regional zooms: zooming out queues hundreds of thousands of OSM elements and triggers 429/504 rejections, so enforce a strict minZoom on the layer in production.
- Public Overpass instances enforce shared fair-use quotas; high-traffic applications should cache responses or host a dedicated Overpass/tile backend.
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.