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.

Esri imagery west of Kraków with four rock reserves outlined in blue, fitted to the map.
A screenshot of the example. Nature reserves: Generalna Dyrekcja Ochrony Środowiska (GDOŚ). Imagery: Esri World Imagery (Esri, Maxar, Earthstar Geographics and the GIS User Community).

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.ts
import { 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] });
    });
  }
}

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

  • writeGetFeature assembles the WFS GetFeature XML document for Rezerwaty requesting EPSG:3857 GeoJSON output.
  • andFilter combines a wildcard likeFilter (*skał*) on the reserve name with a bboxFilter around Kraków.
  • XMLSerializer serialises the request body sent via HTTP POST fetch, and GeoJSON parses the returned features.
  • view.fit zooms to the four matched limestone reserves with 40 pixels of edge padding.

Pitfalls

  • OGC likeFilter comparisons are case-sensitive by default: passing false as the matchCase argument is essential here because the Polish reserve names capitalise Skał / Skałki.
  • Calling GeoJSON readFeatures without projection options requires the server response to arrive already projected in srsName: '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.

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.