Vector data · Angular, React and OpenLayers

Reuse alternate native vector-tile levels

Reuse odd native Mapbox Vector Tile zoom levels across intermediate OpenLayers view zooms with a custom 512px tile matrix and shared styles.

Central Kraków drawn from odd-level vector tiles with pale land-use fills, road and railway strokes, native place labels and local point icons.
A screenshot of the example. OpenFreeMap; © OpenMapTiles; OpenStreetMap contributors, ODbL; Maki icons, CC0.

What this example shows

Starting over Rynek Główny in Kraków and spanning wide regional scales up to street zoom 19, this advanced MVT map renders land cover, roads, railways, place labels and local Maki point icons while storing and fetching only odd native pyramid levels (1, 3, 5, 7, 9, 11 and 13).

When you need it

Offline mobile field packages, low-bandwidth satellite links and compact regional tile archives can slash storage and CDN cache footprint by shipping every second vector-tile zoom level and letting the client overzoom intermediate steps.

Because vector geometries scale cleanly to 2× resolution without pixelation, skipping even tile levels cuts tile counts dramatically while maintaining crisp cartography—provided custom matrix indices and URL zoom numbers stay properly decoupled.

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.

advanced-style.shared.ts
import type { FeatureLike } from 'ol/Feature.js';
import Fill from 'ol/style/Fill.js';
import Icon from 'ol/style/Icon.js';
import Stroke from 'ol/style/Stroke.js';
import Text from 'ol/style/Text.js';
import type { StyleFunction } from 'ol/style/Style.js';
import Style from 'ol/style/Style.js';

export const advancedLayers: string[] = [
  'landcover',
  'landuse',
  'park',
  'water',
  'waterway',
  'aeroway',
  'building',
  'transportation',
  'boundary',
  'place',
  'water_name',
  'poi',
];

const LANDCOVER_COLORS = {
  wood: '#e9eedf',
  grass: '#d8e8c8',
  wetland: '#cde2d7',
  farmland: '#e9eedf',
  sand: '#f2efdb',
  rock: '#ddd',
} as const;

const LANDUSE_COLORS = {
  cemetery: '#e0e4dd',
  hospital: '#fde',
  school: '#f0e8f8',
  kindergarten: '#f0e8f8',
  university: '#f0e8f8',
  education: '#f0e8f8',
  pitch: '#d8e8c8',
  playground: '#d8e8c8',
  stadium: '#d8e8c8',
} as const;

const ROAD_LINE_FAMILIES = {
  primary: 'orange',
  secondary: 'orange',
  tertiary: 'orange',
  motorway: 'orange',
  trunk: 'orange',
  minor: 'gray',
  service: 'gray',
  bridge: 'gray',
  busway: 'gray',
  ferry: 'gray',
  pier: 'gray',
  path: 'brown',
  track: 'brown',
} as const;

const ROAD_LINE_COLORS = {
  orange: '#e9ac77',
  gray: '#cfcdca',
  brown: '#cba',
} as const;

const PLACE_LABELS = {
  continent: { family: 'prominent' },
  country: { family: 'prominent' },
  state: { family: 'state', maxResolution: 4891.96981025128 },
  province: { family: 'state', maxResolution: 4891.96981025128 },
  city: { family: 'city', maxResolution: 1222.99245256282 },
  town: { family: 'town', maxResolution: 305.748113140705 },
  village: { family: 'village', maxResolution: 38.21851414258813 },
  hamlet: { family: 'smallPlace', maxResolution: 19.109257071294063 },
  suburb: { family: 'smallPlace', maxResolution: 19.109257071294063 },
  neighbourhood: { family: 'smallPlace', maxResolution: 19.109257071294063 },
} as const;

const LABEL_STYLES = {
  prominent: { font: 'bold 11px sans-serif', color: '#334', haloWidth: 2 },
  state: { font: '10px sans-serif', color: '#633', haloWidth: 1 },
  city: { font: 'bold 11px sans-serif', color: '#334', haloWidth: 2 },
  town: { font: '9px sans-serif', color: '#333', haloWidth: 1 },
  village: { font: '8px sans-serif', color: '#333', haloWidth: 1 },
  smallPlace: { font: 'bold 9px sans-serif', color: '#633', haloWidth: 1 },
  waterName: { font: 'italic 11px sans-serif', color: '#74aee9', haloWidth: 1 },
} as const;

const WATER_NAME_CLASSES = { bay: true, lake: true, sea: true, strait: true } as const;
const PLACE_RANK_MIN = 1;
const PLACE_RANK_MAX = 31;
const AEROWAY_MAX_RESOLUTION = 76.43702828517625;
const POI_RANK_ONE_MAX_RESOLUTION = 19.109257071294063;
const POI_RANK_TWO_MAX_RESOLUTION = 9.554628535647032;
const WHITE_HALO = 'rgba(255,255,255,0.8)';

type RoadLineFamily = (typeof ROAD_LINE_FAMILIES)[keyof typeof ROAD_LINE_FAMILIES];
type LabelFamily = keyof typeof LABEL_STYLES;
type PoiClass = 'railway' | 'ferry_terminal';

function hasOwnKey<T extends object>(value: T, key: string): key is keyof T & string {
  return Object.prototype.hasOwnProperty.call(value, key);
}

function isPoint(type: string | undefined): boolean {
  return type === 'Point' || type === 'MultiPoint';
}

function isLine(type: string | undefined): boolean {
  return type === 'LineString' || type === 'MultiLineString';
}

function isPolygon(type: string | undefined): boolean {
  return type === 'Polygon' || type === 'MultiPolygon';
}

function actualName(feature: FeatureLike): string | undefined {
  const name = feature.get('name');
  return typeof name === 'string' && name.trim().length > 0 ? name : undefined;
}

function numericLayer(feature: FeatureLike): number {
  const layer = feature.get('layer');
  return typeof layer === 'number' && Number.isFinite(layer) ? layer : 0;
}

function validRank(feature: FeatureLike): number | undefined {
  const rank = feature.get('rank');
  return typeof rank === 'number' && Number.isInteger(rank) && rank >= PLACE_RANK_MIN && rank <= PLACE_RANK_MAX
    ? rank
    : undefined;
}

function roadLineFamily(className: string): RoadLineFamily | 'rail' | undefined {
  if (className === 'rail') return 'rail';
  const baseClass = className.endsWith('_construction') ? className.slice(0, -'_construction'.length) : className;
  return hasOwnKey(ROAD_LINE_FAMILIES, baseClass) ? ROAD_LINE_FAMILIES[baseClass] : undefined;
}

/** Builds bounded, factory-local styles for the finite classes in the local MVT source. */
export function createAdvancedStyle(): StyleFunction {
  const styleCache = new Map<string, Style>();
  const textCache = new Map<LabelFamily, Text>();

  const cachedStyle = (key: string, create: () => Style): Style => {
    const cached = styleCache.get(key);
    if (cached) return cached;
    const style = create();
    styleCache.set(key, style);
    return style;
  };

  const fillStyle = (key: string, color: string, zIndex: number): Style =>
    cachedStyle(key, () => new Style({ fill: new Fill({ color }), zIndex }));

  const strokeStyle = (key: string, color: string, width: number, zIndex: number): Style =>
    cachedStyle(key, () => new Style({ stroke: new Stroke({ color, width }), zIndex }));

  const fillStrokeStyle = (key: string, fillColor: string, strokeColor: string, width: number, zIndex: number): Style =>
    cachedStyle(
      key,
      () =>
        new Style({ fill: new Fill({ color: fillColor }), stroke: new Stroke({ color: strokeColor, width }), zIndex })
    );

  const labelStyle = (family: LabelFamily, name: string, zIndex: number): Style => {
    let text = textCache.get(family);
    if (!text) {
      const config = LABEL_STYLES[family];
      text = new Text({
        font: config.font,
        fill: new Fill({ color: config.color }),
        stroke: new Stroke({ color: WHITE_HALO, width: config.haloWidth }),
      });
      textCache.set(family, text);
    }
    text.setText(name);
    const style = cachedStyle(`label:${family}`, () => new Style({ text, zIndex }));
    style.setZIndex(zIndex);
    return style;
  };

  return (feature: FeatureLike, resolution: number): Style | undefined => {
    const sourceLayer = feature.get('source_layer');
    if (typeof sourceLayer !== 'string') return undefined;

    const geometryType = feature.getGeometry()?.getType();

    if (sourceLayer === 'landcover' && isPolygon(geometryType)) {
      const className = feature.get('class');
      if (typeof className === 'string' && hasOwnKey(LANDCOVER_COLORS, className)) {
        return fillStyle(`landcover:${className}`, LANDCOVER_COLORS[className], 0);
      }
      return undefined;
    }

    if (sourceLayer === 'landuse' && isPolygon(geometryType)) {
      const className = feature.get('class');
      if (typeof className === 'string' && hasOwnKey(LANDUSE_COLORS, className)) {
        return fillStyle(`landuse:${className}`, LANDUSE_COLORS[className], 1);
      }
      return undefined;
    }

    if (sourceLayer === 'park') {
      return isPolygon(geometryType) ? fillStyle('park:polygon', '#d8e8c8', 2) : undefined;
    }

    if (sourceLayer === 'water') {
      return isPolygon(geometryType) ? fillStyle('water:polygon', '#a0c8f0', 3) : undefined;
    }

    if (sourceLayer === 'waterway') {
      return isLine(geometryType) ? strokeStyle('waterway:line', '#a0c8f0', 1, 4) : undefined;
    }

    if (sourceLayer === 'aeroway') {
      if (isPolygon(geometryType)) return fillStyle('aeroway:polygon', '#f2efeb', 5);
      if (
        isLine(geometryType) &&
        Number.isFinite(resolution) &&
        resolution >= 0 &&
        resolution <= AEROWAY_MAX_RESOLUTION
      ) {
        return strokeStyle('aeroway:line', '#f0ede9', 1, 5);
      }
      return undefined;
    }

    if (sourceLayer === 'building') {
      return isPolygon(geometryType) ? fillStrokeStyle('building:polygon', '#f2eae2', '#dfdbd7', 1, 6) : undefined;
    }

    if (sourceLayer === 'transportation') {
      const className = feature.get('class');
      if (typeof className !== 'string') return undefined;
      const family = roadLineFamily(className);
      if (!family) return undefined;

      if (isPolygon(geometryType)) {
        const style = fillStrokeStyle('transportation:polygon', '#f0ede9', '#cfcdca', 1, 8 + numericLayer(feature));
        style.setZIndex(8 + numericLayer(feature));
        return style;
      }

      if (isLine(geometryType)) {
        const color = family === 'rail' ? '#bbb' : ROAD_LINE_COLORS[family];
        const width = family === 'rail' ? 2 : 1;
        const baseZIndex = family === 'rail' ? 20 : 10;
        const style = strokeStyle(`transportation:line:${family}`, color, width, baseZIndex);
        style.setZIndex(baseZIndex + numericLayer(feature));
        return style;
      }
      return undefined;
    }

    if (sourceLayer === 'boundary' && isLine(geometryType)) {
      const color = feature.get('maritime') === 1 ? '#a0c8f0' : '#9e9cab';
      return strokeStyle(`boundary:${color}`, color, 1, 30);
    }

    if (sourceLayer === 'place' && isPoint(geometryType) && Number.isFinite(resolution) && resolution >= 0) {
      const className = feature.get('class');
      if (typeof className !== 'string' || !hasOwnKey(PLACE_LABELS, className)) return undefined;
      const config = PLACE_LABELS[className];
      if ('maxResolution' in config && resolution > config.maxResolution) return undefined;
      const name = actualName(feature);
      const rank = validRank(feature);
      if (!name || rank === undefined) return undefined;
      return labelStyle(config.family, name, 40 + PLACE_RANK_MAX - rank);
    }

    if (sourceLayer === 'water_name' && isPoint(geometryType)) {
      const className = feature.get('class');
      const name = actualName(feature);
      if (typeof className !== 'string' || !hasOwnKey(WATER_NAME_CLASSES, className) || !name) return undefined;
      return labelStyle('waterName', name, 38);
    }

    if (sourceLayer === 'poi' && geometryType === 'Point' && Number.isFinite(resolution) && resolution >= 0) {
      const className = feature.get('class');
      const rank = feature.get('rank');
      if ((className !== 'railway' && className !== 'ferry_terminal') || (rank !== 1 && rank !== 2)) return undefined;
      if (rank === 1 && resolution > POI_RANK_ONE_MAX_RESOLUTION) return undefined;
      if (rank === 2 && resolution > POI_RANK_TWO_MAX_RESOLUTION) return undefined;

      const poiClass = className as PoiClass;
      const style = cachedStyle(`poi:${poiClass}`, () => {
        const filename = poiClass === 'railway' ? 'rail-15.svg' : 'ferry-15.svg';
        const image = new Icon({
          src: new URL(`assets/krakow/maki/${filename}`, document.baseURI).href,
          width: 15,
          height: 15,
        });
        return new Style({ image, zIndex: 80 - rank });
      });
      style.setZIndex(80 - rank);
      return style;
    }

    return undefined;
  };
}
mapbox-vector-tiles-advanced.html
<aol-map height="480px" ariaLabel="Odd-level vector tiles around Kraków">
  <aol-interaction-default />
  <aol-control-defaults [attributionOptions]="attributionOptions" />
  <aol-view projection="EPSG:3857" [zoom]="15" [minZoom]="1" [maxZoom]="19">
    <aol-coordinate [x]="19.9373" [y]="50.0617" srid="EPSG:4326" />
  </aol-view>
  <aol-layer-vectortile background="#f8f4f0" [declutter]="true" [style]="style">
    <aol-source-vectortile projection="EPSG:3857" [wrapX]="false" [tileUrlFunction]="tileUrl" [attributions]="credit">
      <aol-format-mvt layerName="source_layer" [layers]="layers" />
      <aol-tilegrid
        [extent]="grid.extent"
        [resolutions]="grid.resolutions"
        [minZoom]="grid.minZoom"
        [tileSize]="grid.tileSize"
      />
    </aol-source-vectortile>
  </aol-layer-vectortile>
</aol-map>
mapbox-vector-tiles-advanced.scss
:host {
  display: block;
}
mapbox-vector-tiles-advanced.shared.ts
import type { TileCoord } from 'ol/tilecoord.js';
import type { Options } from 'ol/tilegrid/TileGrid.js';
import { get as getProjection } from 'ol/proj.js';
import { grid, tiles } from '../../../assets/krakow/openmaptiles-odd/metadata.json';

/** A matrix index is half a view zoom; 512-pixel source cells use native zoom 2 * index - 1. */
export const oddGridOptions: Options = {
  extent: getProjection(grid.projection)?.getExtent(),
  resolutions: Array.from({ length: grid.maxMatrix + 1 }, (_, index) => 156543.03392804097 / 2 ** (2 * index)),
  minZoom: grid.minMatrix,
  tileSize: grid.logicalTileSize,
};

const cells = new Map(tiles.map((tile) => [`${(tile.z + 1) / 2}/${tile.x}/${tile.y}`, tile.asset]));

/** The lookup shares retained native13 cells and refuses unsupported, malformed or absent coordinates. */
export function oddTileUrl(coordinate: TileCoord): string | undefined {
  if (
    coordinate.length !== 3 ||
    !Number.isSafeInteger(coordinate[0]) ||
    !Number.isSafeInteger(coordinate[1]) ||
    !Number.isSafeInteger(coordinate[2])
  )
    return undefined;
  const asset = cells.get(coordinate.join('/'));
  return asset ? new URL(`assets/krakow/${asset}`, document.baseURI).href : undefined;
}
mapbox-vector-tiles-advanced.ts
import { ChangeDetectionStrategy, Component } from '@angular/core';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  FormatMVTComponent,
  LayerVectorTileComponent,
  MapComponent,
  SourceVectorTileComponent,
  TileGridComponent,
  ViewComponent,
} from 'cc-openlayers';
import { attributionOptions, sourceCredit } from '../mapbox-vector-tiles/mapbox-vector-tiles.shared';
import { advancedLayers, createAdvancedStyle } from './advanced-style.shared';
import { oddGridOptions, oddTileUrl } from './mapbox-vector-tiles-advanced.shared';

@Component({
  selector: 'app-mapbox-vector-tiles-advanced',
  imports: [
    MapComponent,
    ViewComponent,
    CoordinateComponent,
    LayerVectorTileComponent,
    SourceVectorTileComponent,
    FormatMVTComponent,
    TileGridComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './mapbox-vector-tiles-advanced.html',
  styleUrl: './mapbox-vector-tiles-advanced.scss',
})
export class MapboxVectorTilesAdvanced {
  protected readonly style = createAdvancedStyle();
  protected readonly grid = oddGridOptions;
  protected readonly tileUrl = oddTileUrl;
  protected readonly layers = advancedLayers;
  protected readonly attributionOptions = attributionOptions;
  protected readonly credit = sourceCredit;
}

Architecture and OpenLayers mechanics

A custom 512-pixel TileGrid maps matrix index i (1..7, matching the grid’s minimum matrix) to native XYZ URL zoom 2*i - 1 (1, 3, 5, 7, 9, 11, 13), allowing view zooms 14 through 19 to reuse the six native level-13 cells of the 37-cell OpenFreeMap fixture.

Instead of allocating unbounded per-feature style caches, a bounded per-map style factory reuses shared polygon, stroke and Text style instances—mutating label strings per draw call and caching only the two supported local CC0 Maki icon categories.

How it works

  • A custom 512-pixel tile matrix maps grid level i to odd native XYZ zooms (1, 3, 5, 7, 9, 11 and 13) and overzooms level 13 through view zoom 19.
  • Thirty-seven verified OpenFreeMap MVT cells supply real OpenMapTiles geometry and attributes across regional and city scales.
  • A bounded imperative style factory reuses shared polygon, line and text Style instances—updating label text dynamically and caching two local Maki icon types.
  • Remapping MVT group names to source_layer preserves numeric transport layer ordering alongside class, name, rank and maritime fields.

Pitfalls

  • Never pass the sequential TileGrid matrix index (1..7) directly as the {z} URL parameter when levels are skipped—map matrix indices explicitly to native XYZ zoom numbers (1, 3, ..., 13) or tiles will land in completely wrong geographic cells.
  • Overzooming level-13 vector tiles to zoom 19 keeps strokes razor-sharp and eliminates extra HTTP requests, but only displays features already generalised into level 13.
  • Avoid unbounded style caches keyed by unique feature text or ID, which leak memory during long pan sessions; mutate text on shared Style instances instead.

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.