Vector data · Angular, React and OpenLayers

Tile GeoJSON in the browser

Slice a local GeoJSON dataset into dynamic vector tiles inside the browser using geojson-vt and render them via an OpenLayers VectorTileSource.

Cut local GeoJSON into vector tiles and display them through an OpenLayers vector tile source.
A screenshot of the example. Map data © OpenStreetMap contributors.

What this example shows

Over OpenStreetMap, assets/poland/krakow.geojson is indexed in memory by geojson-vt and served as 512-pixel vector tiles straight from the browser, rendered through an OpenLayers vector-tile layer.

When you need it

Medium-to-large GeoJSON datasets (several megabytes of complex administrative polygons or parcel boundaries) often arrive from a static file or REST endpoint without a dedicated .mvt tile server behind them, yet bog down standard untiled VectorLayer rendering.

Indexing the GeoJSON once in memory with geojson-vt gives OpenLayers fast per-tile clipping and zoom-dependent Douglas–Peucker simplification with zero backend infrastructure.

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.

geojson-vt.html
<aol-map height="480px"
  ><aol-interaction-default /><aol-control-defaults /><aol-view [zoom]="12"
    ><aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" /></aol-view
  ><aol-layer-tile><aol-source-osm /></aol-layer-tile
></aol-map>
@if (error()) {
  <p role="alert">{{ error() }}</p>
}
geojson-vt.shared.ts
import GeoJSONVT, { type LegacyFeature } from 'geojson-vt';
import type { FeatureCollection, Feature as GeoFeature, Geometry } from 'geojson';
import type Map from 'ol/Map';
import Feature from 'ol/Feature';
import VectorTile from 'ol/VectorTile';
import GeoJSON from 'ol/format/GeoJSON';
import Projection from 'ol/proj/Projection';
import VectorTileLayer from 'ol/layer/VectorTile';
import VectorTileSource from 'ol/source/VectorTile';
function convert(item: LegacyFeature): GeoFeature {
  let geometry: Geometry;
  if (item.type === 1)
    geometry =
      item.geometry.length === 1
        ? { type: 'Point', coordinates: item.geometry[0] }
        : { type: 'MultiPoint', coordinates: item.geometry };
  else if (item.type === 2)
    geometry =
      item.geometry.length === 1
        ? { type: 'LineString', coordinates: item.geometry[0] }
        : { type: 'MultiLineString', coordinates: item.geometry };
  else geometry = { type: 'Polygon', coordinates: item.geometry };
  return { type: 'Feature', geometry, properties: item.tags, id: item.id };
}
export function tiledSource(data: FeatureCollection): VectorTileSource<Feature> {
  const index = new GeoJSONVT(data, { extent: 4096 });
  const format = new GeoJSON({
    dataProjection: new Projection({ code: 'TILE_PIXELS', units: 'tile-pixels', extent: [0, 0, 4096, 4096] }),
  });
  const source = new VectorTileSource<Feature>({
    format,
    tileUrlFunction: (coord) => JSON.stringify(coord),
    tileLoadFunction: (tile, url) => {
      const coord = JSON.parse(url) as [number, number, number];
      const data = index.getTile(...coord);
      const features = format.readFeatures(
        { type: 'FeatureCollection', features: data?.features.map(convert) ?? [] },
        { extent: source.getTileGrid()?.getTileCoordExtent(coord), featureProjection: 'EPSG:3857' }
      );
      (tile as VectorTile<Feature>).setFeatures(features);
    },
  });
  return source;
}
export function bind(map: Map, onError: (message: string) => void = () => undefined): () => void {
  const controller = new AbortController();
  let layer: VectorTileLayer | undefined;
  void fetch('assets/poland/krakow.geojson', { signal: controller.signal })
    .then((response) => {
      if (!response.ok) throw new Error(String(response.status));
      return response.json();
    })
    .then((data: FeatureCollection) => {
      if (controller.signal.aborted) return;
      layer = new VectorTileLayer({
        source: tiledSource(data),
        style: {
          'fill-color': 'rgba(59,130,246,0.2)',
          'stroke-color': '#2563eb',
          'stroke-width': 2,
          'circle-radius': 5,
          'circle-fill-color': '#2563eb',
        },
      });
      map.addLayer(layer);
    })
    .catch(() => {
      if (!controller.signal.aborted) onError('GeoJSON data could not be loaded.');
    });
  return () => {
    controller.abort();
    if (layer) map.removeLayer(layer);
  };
}
geojson-vt.ts
import {
  ChangeDetectionStrategy,
  Component,
  DestroyRef,
  inject,
  signal,
  viewChild,
  type AfterViewInit,
} from '@angular/core';
import {
  MapComponent,
  ViewComponent,
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerTileComponent,
  SourceOsmComponent,
} from 'cc-openlayers';
import { bind } from './geojson-vt.shared';
@Component({
  selector: 'app-geojson-vt',
  imports: [
    MapComponent,
    ViewComponent,
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    LayerTileComponent,
    SourceOsmComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './geojson-vt.html',
})
export class GeojsonVt implements AfterViewInit {
  readonly error = signal('');
  private readonly map = viewChild.required(MapComponent);
  private readonly destroy = inject(DestroyRef);
  ngAfterViewInit(): void {
    this.destroy.onDestroy(bind(this.map().instance, (message) => this.error.set(message)));
  }
}

Architecture and OpenLayers mechanics

The example builds new GeoJSONVT(data, { extent: 4096 }) from the loaded GeoJSON, then its tileLoadFunction asks index.getTile(...coord) for each requested cell and reads the 0..4096 tile-pixel geometries through OpenLayers' GeoJSON format as units: 'tile-pixels', producing full Feature instances in a VectorTileSource<Feature> rather than RenderFeatures.

How it works

  • The geojson-vt library indexes the loaded GeoJSON in memory and supplies clipped, simplified per-tile geometry on demand to the OpenLayers vector-tile source.

Pitfalls

  • Client-side geojson-vt accelerates panning and rendering after load, but the browser still has to download and parse the entire raw GeoJSON file up front—switch to pre-built server/static MVT or PMTiles archives when datasets exceed tens of megabytes.

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.