Vector data · Angular, React and OpenLayers
A filtered WFS GetFeature request
Post a filtered XML WFS GetFeature query with spatial and case-insensitive name filters in OpenLayers and fit the view to matching reserves.

What this example shows
Over Esri satellite imagery west of Kraków, an OGC WFS XML search combining a bounding-box filter with a wildcard name pattern (*skał*) locates four limestone rock nature reserves—Panieńskie Skały, Bielańskie Skałki, Skałki Przegorzalskie and Skała Kmity—outlines them in blue, and frames all four cleanly inside the viewport.
When you need it
Search bars, parcel finders and attribute filter forms need the WFS server itself to evaluate spatial and text predicates so only matching records cross the network.
Generating OGC Filter Encoding XML via OpenLayers’ WFS format gives you rich server-side AND, OR, PropertyIsLike and spatial BBOX queries without hand-writing XML strings.
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-wfs-getfeature.tsimport { afterNextRender, ChangeDetectionStrategy, Component, viewChild } from '@angular/core';
import { and as andFilter, bbox as bboxFilter, like as likeFilter } from 'ol/format/filter';
import GeoJSON from 'ol/format/GeoJSON';
import WFS from 'ol/format/WFS';
import { transformExtent } from 'ol/proj';
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';
/** Kraków and its surroundings, in Web Mercator. */
const KRAKOW_AREA = transformExtent([19.79, 49.97, 20.22, 50.13], 'EPSG:4326', 'EPSG:3857');
/** A GetFeature request for the nature reserves around Kraków whose names contain "skał" (rock), in any case. */
function rockReserves(): string {
const request = new WFS().writeGetFeature({
srsName: 'EPSG:3857',
featureNS: 'GDOS',
featurePrefix: 'GDOS',
featureTypes: ['Rezerwaty'],
outputFormat: 'application/json',
filter: andFilter(
likeFilter('nazwa', '*skał*', '*', '.', '!', false),
bboxFilter('geom', KRAKOW_AREA, 'EPSG:3857')
),
});
return new XMLSerializer().serializeToString(request);
}
/**
* A WFS GetFeature request with a filter, posted to the WFS of the General Directorate for Environmental Protection
* (GDOŚ): a `PropertyIsLike` on the name and a `BBOX` around Kraków find four rock reserves west of the centre, three
* in the Zwierzyniec district and one just beyond the city in Zabierzów, and the view fits the features it answers
* with a margin that keeps them clear of the map's edges and controls.
*/
@Component({
selector: 'app-vector-wfs-getfeature',
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]="12" [maxZoom]="19">
<aol-coordinate [x]="19.9368" [y]="50.0614" 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
attributions='Nature reserves: <a href="https://www.gdos.gov.pl/" target="_blank">GDOŚ</a>'
/>
</aol-layer-vector>
</aol-map>
`,
})
export class VectorWfsGetfeature {
protected readonly style = new Style({ stroke: new Stroke({ color: 'rgba(0, 0, 255, 1.0)', width: 2 }) });
private readonly map = viewChild.required(MapComponent);
private readonly reserves = viewChild.required(SourceVectorComponent);
constructor() {
// post the request, then add the received features to the layer and fit the view to them, 40 pixels inside the map
afterNextRender(async () => {
const response = await fetch('https://sdi.gdos.gov.pl/wfs', { method: 'POST', body: rockReserves() });
const source = this.reserves().instance;
source.addFeatures(new GeoJSON().readFeatures(await response.json()));
const view = this.map().instance.getView();
view.fit(source.getExtent(), { padding: [40, 40, 40, 40] });
});
}
} 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-wfs-getfeature.react.tsximport { useEffect, useState } from 'react';
import type { Extent } from 'ol/extent.js';
import { and as andFilter, bbox as bboxFilter, like as likeFilter } from 'ol/format/filter.js';
import GeoJSON from 'ol/format/GeoJSON.js';
import WFS from 'ol/format/WFS.js';
import type OLMap from 'ol/Map.js';
import { transformExtent } from 'ol/proj.js';
import type OLVectorSource from 'ol/source/Vector.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';
/** Kraków and its surroundings, in Web Mercator. */
const KRAKOW_AREA = transformExtent([19.79, 49.97, 20.22, 50.13], 'EPSG:4326', 'EPSG:3857');
/** A GetFeature request for the nature reserves around Kraków whose names contain "skał" (rock), in any case. */
function rockReserves(): string {
const request = new WFS().writeGetFeature({
srsName: 'EPSG:3857',
featureNS: 'GDOS',
featurePrefix: 'GDOS',
featureTypes: ['Rezerwaty'],
outputFormat: 'application/json',
filter: andFilter(
likeFilter('nazwa', '*skał*', '*', '.', '!', false),
bboxFilter('geom', KRAKOW_AREA, 'EPSG:3857')
),
});
return new XMLSerializer().serializeToString(request);
}
const style = new Style({ stroke: new Stroke({ color: 'rgba(0, 0, 255, 1.0)', width: 2 }) });
/**
* A WFS GetFeature request with a filter, posted to the WFS of the General Directorate for Environmental Protection
* (GDOŚ): a `PropertyIsLike` on the name and a `BBOX` around Kraków find four rock reserves west of the centre, three
* in the Zwierzyniec district and one just beyond the city in Zabierzów, and the view fits the features it answers
* with a margin that keeps them clear of the map's edges and controls.
*/
export function VectorWfsGetfeature() {
// The map and the source reach the effect as state: each exists only after its own commit.
const [map, setMap] = useState<OLMap | null>(null);
const [reserves, setReserves] = useState<OLVectorSource | null>(null);
useEffect(() => {
if (!map || !reserves) return;
// StrictMode and a replaced source run the effect again: a request that is no longer wanted adds nothing.
let current = true;
// post the request, then add the received features to the layer and fit the view to them, 40 pixels inside the map
(async () => {
const response = await fetch('https://sdi.gdos.gov.pl/wfs', { method: 'POST', body: rockReserves() });
const features = new GeoJSON().readFeatures(await response.json());
if (!current) return;
reserves.addFeatures(features);
map.getView().fit(reserves.getExtent() as Extent, { padding: [40, 40, 40, 40] });
})();
return () => {
current = false;
};
}, [map, reserves]);
return (
<Map ref={setMap} height="480px">
<DefaultInteractions />
<DefaultControls />
<View zoom={12} maxZoom={19}>
<Coordinate x={19.9368} y={50.0614} 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={style}>
<VectorSource
ref={setReserves}
attributions='Nature reserves: <a href="https://www.gdos.gov.pl/" target="_blank">GDOŚ</a>'
/>
</VectorLayer>
</Map>
);
}How the React version works
Nature reserves around Kraków whose names contain “skał” (rock), fetched by one GetFeature POST with a name and extent filter; the view fits them.
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 |
|---|---|
afterNextRender with the request and viewChild of the map and the source | useEffect on [map, reserves] held in state (ref={setMap}), because refs are empty at the first effect; a flag ignores the answer of a replaced effect |
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
writeGetFeature constructs a typed WFS query targeting the Rezerwaty feature type in EPSG:3857 with GeoJSON output, combining a case-insensitive likeFilter (*skał*) and a spatial bboxFilter inside andFilter.
Serialising the XML node via XMLSerializer and posting it with fetch returns matching features decoded by GeoJSON, after which view.fit frames their combined extent with 40 pixels of padding.
How it works
writeGetFeatureassembles the WFS GetFeature XML document forRezerwatyrequestingEPSG:3857GeoJSON output.andFiltercombines a wildcardlikeFilter(*skał*) on the reserve name with abboxFilteraround Kraków.XMLSerializerserialises the request body sent via HTTP POSTfetch, andGeoJSONparses the returned features.view.fitzooms to the four matched limestone reserves with 40 pixels of edgepadding.
Pitfalls
- OGC
likeFiltercomparisons are case-sensitive by default: passingfalseas the matchCase argument is essential here because the Polish reserve names capitalise Skał / Skałki. - Calling
GeoJSONreadFeatures without projection options requires the server response to arrive already projected insrsName: 'EPSG:3857'. - Sending the POST body with a default text Content-Type avoids triggering a browser CORS OPTIONS preflight that an explicit application/xml header would require.
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.