~/dev.log

Frontend Architecture

MapLibre GL: Vector Maps & Clean Angular Architecture

2026-11-24•9 min read•#MapLibre#Angular#Signals#NgRx SignalStore#GIS#WebGL

GPU-accelerated open-source vector maps with MapLibre GL JS—and a clean, testable Angular Signals & NgRx SignalStore architecture for real-time layers.

MapLibre in 30 Seconds

MapLibre GL JS is an open-source, WebGL-powered mapping engine for rendering vector tiles, 3D globes, and live GeoJSON at 60fps without vendor lock-in. Because MapLibre is imperative while Angular is declarative and Signal-driven, pairing them cleanly requires separating reactive state (NgRx SignalStore), per-layer GeoJSON adapters (MapLayerAdapter), and a thin host component synchronized with single-responsibility Angular effects.

Introduction

Companion Reference Guide for the Spring Traffic Control series—an exploration playground built to test AG-UI and A2UI hands-on and distill clean, production-worthy patterns for Spring and Angular apps.

MapLibre GL JS is an open-source, BSD-3-Clause JavaScript library for rendering interactive, GPU-accelerated vector and raster maps in the browser using WebGL. Born as a community-governed fork of Mapbox GL JS v1, it implements the open MapLibre Style Specification and runs heavy tile parsing and layout work off the main thread in a dedicated Web Worker.

Unlike traditional DOM- or SVG-based mapping libraries that struggle once you plot a few hundred markers, MapLibre draws vector tiles, labels, polylines, and thousands of live GeoJSON features directly on the GPU—giving you smooth 60fps zooming, rotation, pitch, and seamless switching between flat Mercator and 3D Globe projections with zero proprietary tile lock-in.

Comparison of MapLibre GL JS, Leaflet, Mapbox GL JS v2+, and Google Maps JS API across rendering engine, licensing and cost, provider lock-in, globe and 3D pitch, and high-density live data


How Can MapLibre Help Me?

Whether you are plotting live aviation telemetry, logistics fleets, store locators, or geographic dashboards, MapLibre solves four core mapping challenges out of the box:

1. GPU-Accelerated 60fps Vector Rendering

Vector tiles carry geometry and metadata rather than pre-baked PNG squares. MapLibre styles and renders them directly on the GPU, keeping text crisp at fractional zoom levels, rotating labels smoothly, and handling thousands of dynamic markers or flight tracks without DOM bloat.

2. Open Standards & Zero Vendor Lock-In

Because MapLibre speaks the open MapLibre Style Specification, your map code is completely decoupled from your tile provider. You can start with free open styles (such as OpenFreeMap), serve self-hosted PMTiles from static object storage, or switch to commercial providers like MapTiler or Stadia Maps by swapping a single style URL.

3. Real-Time GeoJSON & Data-Driven Styling

MapLibre treats GeoJSON as a first-class live data source. Calling source.setData(featureCollection) updates geometry and feature properties in place, while declarative style expressions (match, interpolate, case) dynamically drive icon rotation, colors, line widths, and label visibility straight from feature properties.

4. Built-In Mercator & Globe Projections

Global datasets—such as intercontinental flight corridors, satellite ground tracks, or day/night terminators—look distorted on a flat Mercator projection. MapLibre supports switching between 'mercator' and 'globe' projections at runtime with a single call (map.setProjection({ type: 'globe' })).


Core MapLibre Concepts

Before integrating MapLibre into a framework like Angular, it helps to understand the four building blocks that govern every MapLibre instance.

1. Style JSON (The Basemap Contract)

Every Map boots from a Style—either a URL pointing to a JSON document or an inline style object. The style declares the basemap's tile sources, ordered visual layers, sprite sheets (icons), glyphs (SDF fonts for crisp rotated labels), and optional projection.

2. Sources vs. Layers

MapLibre strictly separates data from presentation:

  • Sources hold raw geographic data (vector, raster, geojson, image). A single geojson source can store hundreds of airports or live aircraft positions.
  • Layers reference a source by ID and declare how to paint it (fill, line, symbol, circle, heatmap). Multiple layers can share one source—for example, a stations-icons symbol layer and a stations-labels text layer reading from the same stations GeoJSON source.

3. Camera, Coordinates & Controls

MapLibre follows the GeoJSON coordinate order: [longitude, latitude] (not [lat, lng]). Camera state is defined by center, zoom, bearing, and pitch, and animated with flyTo(...) for point focus or fitBounds(...) for framing a bounding box. Standard UI widgets such as NavigationControl attach directly to map corners.

4. Lifecycle Events & Cleanup

A MapLibre Map loads its style asynchronously. Trying to add custom sources or layers before the style is parsed will throw—always wait for map.on('style.load', ...). Likewise, pointer listeners (map.on('click', layerId, handler)) should be unbound with map.off(...), and the WebGL context must be released with map.remove() when the map unmounts.

import { Map as MapLibreMap, NavigationControl } from 'maplibre-gl';
import 'maplibre-gl/dist/maplibre-gl.css';

const map = new MapLibreMap({
  container: 'map',
  style: 'https://tiles.openfreemap.org/styles/liberty',
  center: [4.764, 52.308], // [longitude, latitude] — Amsterdam Schiphol
  zoom: 6,
});

map.addControl(new NavigationControl(), 'bottom-right');

map.on('style.load', () => {
  map.setProjection({ type: 'globe' });

  map.addSource('stations', {
    type: 'geojson',
    data: { type: 'FeatureCollection', features: [] },
  });

  map.addLayer({
    id: 'stations-points',
    type: 'circle',
    source: 'stations',
    paint: {
      'circle-radius': 6,
      'circle-color': '#7aa2f7',
      'circle-stroke-width': 2,
      'circle-stroke-color': '#1a1b26',
    },
  });
});

Clean Angular Architecture With Signals & NgRx SignalStore

MapLibre GL is an imperative WebGL engine: you instantiate a Map, add GeoJSON sources, attach styled layers, bind pointer listeners, and call setData() or flyTo() directly on the instance.

Angular 22, on the other hand, is declarative and Signal-driven. When teams drop MapLibre straight into a single MapComponent, it quickly turns into a 1,000-line tangle of HTTP subscriptions, style.load race conditions, duplicated click handlers, and state that external controls—like side panels, URL query params, or an AG-UI agent—cannot drive cleanly.

The fix is a disciplined three-part split:

  1. Central MapStore (signalStore) — owns shared map state (projection, layer order & visibility, camera flyTo / fitBounds, active selections) with zero MapLibre imports.
  2. One folder per visual layer (*.config.ts, *.store.ts, *.layer.ts) — each layer derives its own typed GeoJSON in Signals and adapts it to MapLibre behind a small MapLayerAdapter interface.
  3. Thin MapPage host — initializes the WebGL canvas once in afterNextRender(), reacts to MapStore and layer stores via single-responsibility effect() hooks, and tears everything down cleanly on destroy.

MapLibre GL and Angular Signals three-tier architecture: Declarative NgRx SignalStores (Domain Stores feeding Per-Layer SignalStores and a central MapStore) flow through MapLayerAdapter services and a thin MapPage Host using afterNextRender and Angular effects into the MapLibre GL JS WebGL Canvas, with map click events looping back into store state

Central Map State (MapStore)

Keep imperative MapLibre API calls out of your stores. Instead, model projections, layer ordering, and camera requests as plain reactive state:

export type MapProjection = 'mercator' | 'globe';
export type MapLayerId = 'day-night' | 'flight-paths' | 'stations' | 'flight-track' | 'flight-states';

export interface MapCameraTarget {
  readonly longitude: number;
  readonly latitude: number;
  readonly zoom?: number;
}

export interface MapCameraBounds {
  readonly sw: [number, number]; // [minLon, minLat]
  readonly ne: [number, number]; // [maxLon, maxLat]
  readonly maxZoom?: number;
}

In MapStore, flyTo and fitBounds are mutually exclusive so point-focus moves and multi-feature framing never fight each other:

import { computed } from '@angular/core';
import { patchState, signalStore, withComputed, withMethods, withState } from '@ngrx/signals';

export const MapStore = signalStore(
  { providedIn: 'root' },
  withState(initialState),
  withComputed(({ layers }) => ({
    layerVisibility: computed(
      () => Object.fromEntries(layers().map((l) => [l.id, l.visible])) as Record<MapLayerId, boolean>,
    ),
    layerOrder: computed(() => layers().map((l) => l.id)),
  })),
  withMethods((store) => ({
    setProjection(projection: MapProjection): void {
      patchState(store, { projection });
    },
    toggleLayer(layerId: MapLayerId, visible?: boolean): void {
      patchState(store, (state) => ({
        layers: state.layers.map((layer) =>
          layer.id === layerId ? { ...layer, visible: visible ?? !layer.visible } : layer,
        ),
      }));
    },
    flyTo(target: MapCameraTarget): void {
      patchState(store, { cameraTarget: target, cameraBounds: null });
    },
    fitBounds(bounds: MapCameraBounds): void {
      patchState(store, { cameraBounds: bounds, cameraTarget: null });
    },
    selectStation(code: string | null): void {
      patchState(store, { selectedStationCode: code });
    },
  })),
);

Because MapStore has no DOM or WebGL dependencies, every state transition is pure, predictable, and trivial to unit test.


Safe Initialization & the MapLayerAdapter Pattern

Mounting MapLibre Safely in Angular 22

Three details matter when mounting MapLibre inside a modern Angular (esbuild/Vite) application with ChangeDetectionStrategy.OnPush:

  1. Predictable Web Worker bundling: Call setWorkerUrl(...) before creating new MapLibreMap(...) so MapLibre loads its worker from a static asset path instead of breaking under bundler worker transforms.
  2. Browser-only initialization: Mount inside afterNextRender() using a viewChild() container reference, and guard with a quick supportsWebGl() check so SSR and unit tests (Vitest/jsdom) never crash.
  3. Style readiness, responsive resize & cleanup: Track styleReady = signal(false), flip it to true inside map.on('style.load', ...), attach a ResizeObserver so side-panel toggles never leave blank canvas edges, and detach all adapters plus call map.remove() inside DestroyRef.onDestroy.
@Component({
  selector: 'app-map-page',
  templateUrl: './map-page.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MapPage {
  private readonly mapStore = inject(MapStore);
  private readonly theme = inject(ThemeStore);
  private readonly destroyRef = inject(DestroyRef);

  private readonly mapContainer = viewChild<ElementRef<HTMLElement>>('mapContainer');
  private readonly mapInstance = signal<MapLibreMap | null>(null);
  private readonly styleReady = signal(false);
  private appliedDarkMode: boolean | null = null;

  constructor() {
    afterNextRender(() => this.initMap());
  }

  private initMap(): void {
    const container = this.mapContainer()?.nativeElement;
    if (!container || !this.supportsWebGl()) return;

    setWorkerUrl(MAP_CONFIG.workerUrl);

    const isDark = this.theme.isDark();
    this.appliedDarkMode = isDark;

    const map = new MapLibreMap({
      container,
      style: isDark ? MAP_CONFIG.styles.dark : MAP_CONFIG.styles.light,
      center: MAP_CONFIG.defaultCenter,
      zoom: MAP_CONFIG.defaultZoom,
    });

    map.addControl(new NavigationControl(), 'bottom-right');

    // Flip styleReady once the basemap loads so reactive effects sync projection & layers
    map.on('style.load', () => {
      map.resize();
      this.styleReady.set(true);
    });

    if (typeof ResizeObserver !== 'undefined') {
      const observer = new ResizeObserver(() => map.resize());
      observer.observe(container);
      this.destroyRef.onDestroy(() => observer.disconnect());
    }

    this.destroyRef.onDestroy(() => {
      for (const adapter of Object.values(this.layerAdapters)) {
        adapter.detach(map);
      }
      map.remove();
      this.mapInstance.set(null);
    });

    this.mapInstance.set(map);
  }
}

The MapLayerAdapter Pattern

Every visual concern (day-night, flight-paths, stations, flight-states, flight-track) lives in its own feature folder with three small files:

  1. <layer>.config.ts — source IDs, layer IDs, paint/layout constants, and icon definitions.
  2. <layer>.store.ts — @ngrx/signals store deriving typed GeoJSON (FeatureCollection) from domain stores via computed().
  3. <layer>.layer.ts — injectable service implementing MapLayerAdapter.
export interface MapLayerAdapter {
  readonly id: MapLayerId;
  readonly mapLayerIds: readonly string[];
  attach(map: MapLibreMap): void;
  sync(map: MapLibreMap): void;
  setVisible(map: MapLibreMap, visible: boolean): void;
  detach(map: MapLibreMap): void;
}

Example Adapter (StationsLayer)

Each adapter stays small and focused: attach() creates the GeoJSON source and registers layers plus pointer listeners, sync() pushes the latest computed() GeoJSON into source.setData(...), setVisible() toggles layout visibility, and detach() removes listeners, layers, and sources cleanly:

@Injectable({ providedIn: 'root' })
export class StationsLayer implements MapLayerAdapter {
  private readonly layerStore = inject(StationsLayerStore);
  private readonly mapStore = inject(MapStore);

  readonly id = STATIONS_LAYER_CONFIG.id;
  readonly mapLayerIds = [
    STATIONS_LAYER_CONFIG.iconLayerId,
    STATIONS_LAYER_CONFIG.labelLayerId,
  ] as const;

  private boundMap: MapLibreMap | null = null;

  private readonly handleClick = (event: MapLayerMouseEvent): void => {
    const code = event.features?.[0]?.properties?.['code'];
    if (typeof code === 'string' && code.length > 0) {
      this.layerStore.selectStation(code);
      this.mapStore.selectStation(code);
    }
  };

  attach(map: MapLibreMap): void {
    this.boundMap = map;
    if (!map.getSource(STATIONS_LAYER_CONFIG.sourceId)) {
      map.addSource(STATIONS_LAYER_CONFIG.sourceId, {
        type: 'geojson',
        data: this.layerStore.geoJson(),
      });
    }
    this.addLayers(map);
  }

  sync(map: MapLibreMap): void {
    const source = map.getSource(STATIONS_LAYER_CONFIG.sourceId) as GeoJSONSource | undefined;
    source?.setData(this.layerStore.geoJson());
  }

  setVisible(map: MapLibreMap, visible: boolean): void {
    const visibility = visible ? 'visible' : 'none';
    for (const layerId of this.mapLayerIds) {
      if (map.getLayer(layerId)) {
        map.setLayoutProperty(layerId, 'visibility', visibility);
      }
    }
  }

  detach(map: MapLibreMap): void {
    if (this.boundMap === map) this.boundMap = null;
    map.off('click', STATIONS_LAYER_CONFIG.iconLayerId, this.handleClick);
    for (const layerId of this.mapLayerIds) {
      if (map.getLayer(layerId)) map.removeLayer(layerId);
    }
    if (map.getSource(STATIONS_LAYER_CONFIG.sourceId)) {
      map.removeSource(STATIONS_LAYER_CONFIG.sourceId);
    }
  }
}

Async icons tip: If a layer loads an SVG or PNG into map.addImage(...) asynchronously, always guard the callback with if (this.boundMap !== map) return; before calling addLayers(map) so a rapid theme or style switch never attaches stale layers.


Reactive Sync With Angular Effects & Camera Control

In the thin MapPage host, small single-responsibility effect() blocks keep MapLibre synchronized with every Signal change—running only once mapInstance() exists and styleReady() is true:

// 1. Switch basemap style when dark/light mode changes
effect(() => {
  const isDark = this.theme.isDark();
  const map = this.mapInstance();
  if (!map || this.appliedDarkMode === isDark) return;
  this.appliedDarkMode = isDark;
  this.styleReady.set(false);
  map.setStyle(isDark ? MAP_CONFIG.styles.dark : MAP_CONFIG.styles.light);
});

// 2. Sync projection (mercator / globe)
effect(() => {
  const map = this.mapInstance();
  const ready = this.styleReady();
  const projection = this.mapStore.projection();
  if (!map || !ready) return;
  map.setProjection({ type: projection });
});

// 3. Sync layer attachment, visibility, and z-order
effect(() => {
  const map = this.mapInstance();
  const ready = this.styleReady();
  const layers = this.mapStore.layers();
  if (!map || !ready) return;

  const activeIds = new Set(layers.map((l) => l.id));
  for (const [id, adapter] of Object.entries(this.layerAdapters) as [MapLayerId, MapLayerAdapter][]) {
    if (!activeIds.has(id)) adapter.detach(map);
  }

  for (const layer of layers) {
    const adapter = this.layerAdapters[layer.id];
    adapter.attach(map);
    adapter.setVisible(map, layer.visible);
    for (const mlId of adapter.mapLayerIds) {
      if (map.getLayer(mlId)) map.moveLayer(mlId);
    }
  }
});

// 4. Sync a layer's GeoJSON whenever its SignalStore recomputes
effect(() => {
  const map = this.mapInstance();
  const ready = this.styleReady();
  this.stationsLayerStore.geoJson();
  if (!map || !ready) return;
  this.stationsLayer.sync(map);
});

Handling Camera flyTo & fitBounds

Gating camera effects on styleReady() ensures camera animations still fire cleanly when a user—or an AG-UI agent—navigates to /map from another route and sets a selection before the basemap finishes loading:

effect(() => {
  const map = this.mapInstance();
  const ready = this.styleReady();
  const target = this.mapStore.cameraTarget();
  if (!map || !ready || !target) return;

  map.flyTo({
    center: [target.longitude, target.latitude],
    zoom: target.zoom ?? MAP_CONFIG.selectionZoom,
    essential: true,
  });
});

effect(() => {
  const map = this.mapInstance();
  const ready = this.styleReady();
  const bounds = this.mapStore.cameraBounds();
  if (!map || !ready || !bounds) return;

  const container = this.mapContainer()?.nativeElement;
  const sidePad = Math.min(80, Math.floor((container?.clientWidth ?? 1280) * 0.1));
  const vertPad = Math.min(80, Math.floor((container?.clientHeight ?? 720) * 0.15));

  map.fitBounds([bounds.sw, bounds.ne], {
    padding: { top: vertPad, bottom: vertPad, left: sidePad, right: sidePad },
    maxZoom: bounds.maxZoom ?? MAP_CONFIG.selectionZoom,
    duration: 900,
    essential: true,
  });
});
Gotchas, Practical Pitfalls & Troubleshooting

map.setStyle(...) wipes all custom sources, layers, and projection

Calling map.setStyle(...) during a light/dark theme toggle tears down every custom GeoJSON source, layer, and projection on the map. Always flip styleReady.set(false) immediately before calling setStyle(...), and flip styleReady.set(true) again inside map.on('style.load', ...) so your reactive effects automatically re-apply setProjection(...) and adapter.attach(map).

Antimeridian wrapping (±180°)

Great-circle arcs (SLERP) or flight tracks crossing the International Date Line will draw a horizontal stripe across the entire map unless you split the coordinate array into a MultiLineString whenever Math.abs(nextLon - prevLon) > 180.

fitBounds padding overflow on narrow screens

On mobile or split-pane viewports, fixed pixel padding (such as left: 420) can exceed the canvas width and cause MapLibre to throw. Always clamp padding as a percentage of container.clientWidth and container.clientHeight.

Unit testing with jsdom

jsdom provides no WebGL context. Guard initMap() with a supportsWebGl() check so your MapPage component specs can verify MapStore state, computed() GeoJSON generation, and camera targets without mocking all of WebGL.

Effortless pairing with AG-UI

Because every map control—projection, layer visibility, camera moves, and feature selection—flows through MapStore and per-layer SignalStores, an AI agent wired over AG-UI can drive the entire map simply by calling the exact same store methods a human click calls, with no imperative Map handle leaked anywhere else in the app.


Summary

MapLibre GL JS gives you open-source, 60fps WebGL vector maps, 3D globes, and live data-driven styling without proprietary tile lock-in. Pairing it cleanly with Angular Signals and NgRx SignalStore comes down to three habits:

  • Keep MapLibre out of your stores: Model projections, layer order, visibility, selections, and mutually exclusive flyTo / fitBounds requests as pure Signal state in MapStore.
  • Isolate every visual layer: Give each layer its own *.config.ts, *.store.ts (computed() GeoJSON), and MapLayerAdapter service with symmetric attach / sync / setVisible / detach lifecycle methods.
  • Sync through a thin host: Mount once in afterNextRender(), gate reactive effect() hooks on styleReady(), observe container resizes, and release WebGL resources cleanly in DestroyRef.onDestroy.