Vector data · Angular, React and OpenLayers

Country polygons from MapServer OGC API Features

Load GeoJSON country polygons dynamically by viewport extent from an OGC API Features collection in OpenLayers with pagination and cleanup.

Poland highlighted red with neighbouring country polygons in green over OpenStreetMap, centred on Kraków at zoom 6.
A screenshot of the example. Natural Earth (public domain); service: MapServer OGC API Features demo. Map data © OpenStreetMap contributors.

What this example shows

Centred on Kraków at zoom 6 over OpenStreetMap, Natural Earth country polygons stream dynamically from MapServer’s OGC API Features service—highlighting Poland in red and neighbouring countries in green alongside a live request status line and full data attributions.

When you need it

OGC API Features is the modern REST/GeoJSON successor to XML-heavy WFS—delivering typed vector geometries and properties over clean /collections/{id}/items HTTP endpoints.

Loading items by visible bounding box keeps initial payloads small and scales cleanly across large feature collections as users pan and zoom.

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.

countries-poland.fixture.json
{
  "features": [
    {
      "geometry": {
        "coordinates": [
          [
            [23.484128, 53.912498],
            [23.527536, 53.470122],
            [23.804935, 53.089732],
            [23.799199, 52.6911],
            [23.199494, 52.486978],
            [23.508003, 52.023647],
            [23.527071, 51.578455],
            [24.029986, 50.705407],
            [23.922758, 50.424882],
            [23.426509, 50.308506],
            [22.518451, 49.476774],
            [22.776419, 49.027396],
            [22.558138, 49.085739],
            [21.607809, 49.470108],
            [20.887956, 49.328773],
            [20.41584, 49.431454],
            [19.825023, 49.217126],
            [19.320713, 49.571575],
            [18.909575, 49.435846],
            [18.853145, 49.49623],
            [18.392914, 49.988629],
            [17.649446, 50.049039],
            [17.554568, 50.362146],
            [16.86877, 50.473974],
            [16.719476, 50.215747],
            [16.176254, 50.422608],
            [16.238627, 50.697733],
            [15.490973, 50.78473],
            [15.016996, 51.106675],
            [14.607099, 51.745189],
            [14.685027, 52.089948],
            [14.4376, 52.624851],
            [14.074522, 52.981263],
            [14.353316, 53.248172],
            [14.119687, 53.75703],
            [14.802901, 54.050707],
            [16.363478, 54.513159],
            [17.622832, 54.851536],
            [18.620859, 54.682606],
            [18.696255, 54.438719],
            [19.660641, 54.426084],
            [20.892245, 54.312525],
            [22.731099, 54.327537],
            [23.243988, 54.220567],
            [23.484128, 53.912498]
          ]
        ],
        "type": "Polygon"
      },
      "id": "1159321179",
      "properties": {
        "abbrev": "Pol.",
        "abbrev_len": "4",
        "adm0_a3": "POL",
        "adm0_a3_is": "POL",
        "adm0_a3_un": "-99",
        "adm0_a3_us": "POL",
        "adm0_a3_wb": "-99",
        "adm0_dif": "0",
        "admin": "Poland",
        "brk_a3": "POL",
        "brk_diff": "0",
        "brk_group": "",
        "brk_name": "Poland",
        "continent": "Europe",
        "economy": "2. Developed region: nonG7",
        "featurecla": "Admin-0 country",
        "fips_10_": "PL",
        "formal_en": "Republic of Poland",
        "formal_fr": "",
        "gdp_md_est": "1052000",
        "gdp_year": "2016",
        "geou_dif": "0",
        "geounit": "Poland",
        "gu_a3": "POL",
        "homepart": "1",
        "income_grp": "1. High income: OECD",
        "iso_a2": "PL",
        "iso_a3": "POL",
        "iso_a3_eh": "POL",
        "iso_n3": "616",
        "labelrank": "3",
        "lastcensus": "2011",
        "level": "2",
        "long_len": "6",
        "mapcolor13": "2",
        "mapcolor7": "3",
        "mapcolor8": "7",
        "mapcolor9": "1",
        "max_label": "7",
        "min_label": "3",
        "min_zoom": "0",
        "name": "Poland",
        "name_alt": "",
        "name_ar": "بولندا",
        "name_bn": "পোল্যান্ড",
        "name_ciawf": "Poland",
        "name_de": "Polen",
        "name_el": "Πολωνία",
        "name_en": "Poland",
        "name_es": "Polonia",
        "name_fr": "Pologne",
        "name_hi": "पोलैंड",
        "name_hu": "Lengyelország",
        "name_id": "Polandia",
        "name_it": "Polonia",
        "name_ja": "ポーランド",
        "name_ko": "폴란드",
        "name_len": "6",
        "name_long": "Poland",
        "name_nl": "Polen",
        "name_pl": "Polska",
        "name_pt": "Polónia",
        "name_ru": "Польша",
        "name_sort": "Poland",
        "name_sv": "Polen",
        "name_tr": "Polonya",
        "name_vi": "Ba Lan",
        "name_zh": "波兰",
        "ne_id": "1159321179",
        "note_adm0": "",
        "note_brk": "",
        "pop_est": "38476269",
        "pop_rank": "15",
        "pop_year": "2017",
        "postal": "PL",
        "region_un": "Europe",
        "region_wb": "Europe & Central Asia",
        "scalerank": "1",
        "sov_a3": "POL",
        "sovereignt": "Poland",
        "su_a3": "POL",
        "su_dif": "0",
        "subregion": "Eastern Europe",
        "subunit": "Poland",
        "tiny": "-99",
        "type": "Sovereign country",
        "un_a3": "616",
        "wb_a2": "PL",
        "wb_a3": "POL",
        "wikidataid": "Q36",
        "wikipedia": "-99",
        "woe_id": "23424923",
        "woe_id_eh": "23424923",
        "woe_note": "Exact WOE match as country"
      },
      "type": "Feature"
    }
  ],
  "links": [
    {
      "href": "https://demo.mapserver.org/cgi-bin/mapserv/localdemo/ogcapi/collections/countries/items?f=json&limit=2&offset=0&bbox=19.7,49.8,20.3,50.3",
      "rel": "self",
      "title": "Items for this collection as GeoJSON",
      "type": "application/geo+json"
    },
    {
      "href": "https://demo.mapserver.org/cgi-bin/mapserv/localdemo/ogcapi/collections/countries/items?f=html&limit=2&offset=0&bbox=19.7,49.8,20.3,50.3",
      "rel": "alternate",
      "title": "Items for this collection as HTML",
      "type": "text/html"
    }
  ],
  "numberMatched": 1,
  "numberReturned": 1,
  "type": "FeatureCollection"
}
mapserver-ogc-features.html
<section class="mapserver-ogc-features">
  <h2>MapServer OGC API features around Poland</h2>
  <p>Country boundaries from MapServer’s public OGC API Features demo.</p>
  <aol-map height="480px" ariaLabel="MapServer OGC API features around Poland">
    <aol-interaction-default />
    <aol-control-defaults [attributionOptions]="attributionOptions" />
    <aol-view [zoom]="view.zoom" [minZoom]="view.minZoom" [maxZoom]="view.maxZoom">
      <aol-coordinate [x]="view.longitude" [y]="view.latitude" srid="EPSG:4326" />
    </aol-view>
    <aol-layer-tile>
      <aol-source-osm [attributions]="osmAttribution" />
    </aol-layer-tile>
    <aol-layer-vector [style]="style">
      <aol-source-vector
        [loader]="loader"
        [strategy]="strategy"
        [wrapX]="false"
        [attributions]="countriesAttribution"
      />
    </aol-layer-vector>
  </aol-map>
  <div class="example-controls">
    <output aria-live="polite">{{ status() }}</output>
  </div>
</section>
mapserver-ogc-features.scss
.mapserver-ogc-features h2 {
  margin: 0 0 0.5rem;
}

.mapserver-ogc-features p {
  margin: 0 0 0.75rem;
}

.mapserver-ogc-features .example-controls output {
  display: block;
}
mapserver-ogc-features.shared.ts
import type { FeatureLike } from 'ol/Feature.js';
import type VectorSource from 'ol/source/Vector.js';
import Fill from 'ol/style/Fill.js';
import type { StyleFunction } from 'ol/style/Style.js';
import Style from 'ol/style/Style.js';
import Stroke from 'ol/style/Stroke.js';
import { ogcItemsLoader, type OgcItemsLoader, type OgcItemsLoaderOptions } from 'cc-openlayers/services';

export const COUNTRIES_ITEMS_URL =
  'https://demo.mapserver.org/cgi-bin/mapserv/localdemo/ogcapi/collections/countries/items?f=json';

export const COUNTRIES_ATTRIBUTION =
  'Data: <a href="https://www.naturalearthdata.com/about/terms-of-use/" target="_blank" rel="noopener noreferrer">Natural Earth (public domain)</a>; ' +
  'service: <a href="https://demo.mapserver.org/cgi-bin/mapserv/localdemo/ogcapi/" target="_blank" rel="noopener noreferrer">MapServer OGC API Features demo</a>';

export const OSM_ATTRIBUTION =
  '© <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener noreferrer">OpenStreetMap</a> contributors';

export const ATTRIBUTION_OPTIONS = { collapsible: false } as const;

export const MAPSERVER_VIEW = { longitude: 19.9368, latitude: 50.0614, zoom: 6, minZoom: 4, maxZoom: 10 } as const;

const polandStyle = new Style({
  fill: new Fill({ color: 'rgba(218, 76, 62, 0.72)' }),
  stroke: new Stroke({ color: '#9a3028', width: 1.4 }),
});

const neighbourStyle = new Style({
  fill: new Fill({ color: 'rgba(109, 157, 116, 0.46)' }),
  stroke: new Stroke({ color: '#647b69', width: 1.1 }),
});

/** Highlights Poland while retaining the surrounding country features returned by the service. */
export const countriesStyle: StyleFunction = (feature: FeatureLike) =>
  feature.get('admin') === 'Poland' ? polandStyle : neighbourStyle;

/** The pinned OpenLayers recipe adapted to the real Natural Earth `countries` collection. */
export function createCountriesItemsLoader(options: OgcItemsLoaderOptions = {}) {
  return ogcItemsLoader(() => COUNTRIES_ITEMS_URL, options);
}

export interface CountriesItemsLoaderOwner extends OgcItemsLoader {
  /** Starts a fresh loader after React StrictMode has replayed effect cleanup. */
  activate(): void;
}

/** Keeps the callback stable while replacing its disposable request loader after effect replay. */
export function createCountriesItemsLoaderOwner(options: OgcItemsLoaderOptions = {}): CountriesItemsLoaderOwner {
  let current = createCountriesItemsLoader(options);
  let disposed = false;

  return {
    loader: function (this: VectorSource, extent, resolution, projection, success, failure) {
      if (disposed) return;
      return current.loader.call(this, extent, resolution, projection, success, failure);
    },
    activate() {
      if (!disposed) return;
      current = createCountriesItemsLoader(options);
      disposed = false;
    },
    dispose() {
      if (disposed) return;
      disposed = true;
      current.dispose();
    },
  };
}
mapserver-ogc-features.ts
import { ChangeDetectionStrategy, Component, DestroyRef, inject, signal } from '@angular/core';
import { bbox } from 'ol/loadingstrategy.js';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerTileComponent,
  LayerVectorComponent,
  MapComponent,
  SourceOsmComponent,
  SourceVectorComponent,
  ViewComponent,
} from 'cc-openlayers';
import {
  ATTRIBUTION_OPTIONS,
  COUNTRIES_ATTRIBUTION,
  MAPSERVER_VIEW,
  OSM_ATTRIBUTION,
  countriesStyle,
  createCountriesItemsLoader,
} from './mapserver-ogc-features.shared';

/** Bbox-loaded Natural Earth country features from MapServer's public OGC API Features demo. */
@Component({
  selector: 'app-mapserver-ogc-features',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    LayerTileComponent,
    LayerVectorComponent,
    MapComponent,
    SourceOsmComponent,
    SourceVectorComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './mapserver-ogc-features.html',
  styleUrl: './mapserver-ogc-features.scss',
})
export class MapserverOgcFeatures {
  private readonly destroyRef = inject(DestroyRef);
  readonly status = signal('Waiting for a visible map area.');

  protected readonly view = MAPSERVER_VIEW;
  protected readonly attributionOptions = ATTRIBUTION_OPTIONS;
  protected readonly countriesAttribution = COUNTRIES_ATTRIBUTION;
  protected readonly osmAttribution = OSM_ATTRIBUTION;
  protected readonly style = countriesStyle;
  protected readonly strategy = bbox;

  private readonly items = createCountriesItemsLoader({
    onState: (state, details) => {
      if (state === 'pending') {
        this.status.set('Loading country features…');
      } else if (state === 'failed') {
        this.status.set('Country features could not be loaded. Pan or zoom to try again.');
      } else {
        this.status.set(details.truncated ? 'Loaded a bounded page of country features.' : 'Country features loaded.');
      }
    },
  });

  protected readonly loader = this.items.loader;

  constructor() {
    this.destroyRef.onDestroy(this.items.dispose);
  }
}

Architecture and OpenLayers mechanics

A shared extent-aware OGC items loader converts the requested Web Mercator box—which automatically includes OpenLayers’ 100-pixel vector render buffer around the screen—into geographic bbox coordinates, follows collection pagination links, decodes returned GeoJSON into the view projection, and manages request timeouts and AbortController cancellation.

Angular disposes of in-flight requests cleanly on component teardown, while the React wrapper preserves callback identity and recreates its disposable loader delegate safely across StrictMode double-invocation.

How it works

  • Natural Earth country outlines around Kraków render Poland in red and neighbours in green as a small-scale OGC API Features demonstration.
  • The shared loader projects the requested extent to geographic degrees, parses GeoJSON into Web Mercator, and handles pagination, timeouts and cancellation.
  • OpenLayers expands the requested extent by the vector layer’s 100-pixel render buffer so features just outside the viewport edge are pre-fetched.
  • Lifecycle cleanup cancels pending fetches on Angular destroy and across React StrictMode effect replays while surfacing clear loading/error states.

Pitfalls

  • Always verify spatial coverage of the chosen OGC collection for your study area—querying a regional collection without features around Kraków returns an empty array even when the server is healthy.
  • Generalised small-scale Natural Earth boundaries illustrate protocol mechanics only and must not be used for cadastral or legal border analysis.
  • Public demonstration servers can throttle or time out unpredictably—surface explicit status messages so users can distinguish network errors from empty areas.

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.