Skip to content
Make with

New in MapLibre GL JS 6.15

Maps in any projection

MapLibre GL JS 6.15 draws maps in your own coordinate system: polar maps, national grids, equal-area world maps, even a flat image. Every map here is live, with its code.

Maps in their own grid

Tiles that NASA and Eurostat already make in their own projection, around the poles and across Europe, plus a scanned map on a flat plane.

Loading the map…

EPSG:3413 · Polar stereographic north

The Arctic, pole in the middle

NASA's Blue Marble from a WMS that renders in the polar grid. Each tile asks for its box in the grid's meters through the {bbox} token. The places and the lines of latitude are plain lng/lat GeoJSON, projected in MapLibre's workers.

  • WMS with {bbox}
  • GeoJSON in the workers
  • Labels
Map code

Plain MapLibre GL JS 6.15 with proj4 and crs-defs, ready to paste into a module: createMap("map") makes the map in the element with the id map. With a bundler, point MapLibre at its worker first, as in the quick start.

import * as maplibregl from "maplibre-gl";
import "maplibre-gl/dist/maplibre-gl.css";
import proj4 from "proj4";
import { EPSG_4326, EPSG_3413 } from "crs-defs";

// NASA GIBS speaks WMS in EPSG:3413: {bbox} becomes each tile's bounds in its meters.
const gibs = (layer: string) =>
  `https://gibs.earthdata.nasa.gov/wms/epsg3413/best/wms.cgi?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&SRS=EPSG:3413&STYLES=&BBOX={bbox}&WIDTH=512&HEIGHT=512&FORMAT=image/png&TRANSPARENT=TRUE&LAYERS=${layer}`;

const places: [string, number, number][] = [
  ["North Pole", 0, 90],
  ["Longyearbyen", 15.63, 78.22],
  ["Nuuk", -51.72, 64.18],
  ["Alert", -62.35, 82.5],
  ["Resolute", -94.83, 74.7],
  ["Murmansk", 33.08, 68.97],
  ["Utqiaġvik", -156.79, 71.29],
  ["Reykjavík", -21.94, 64.15],
];

/** Lines of latitude and longitude as GeoJSON, with a point every degree so they curve with the projection. */
function graticule(step: number, [south, north]: [number, number]): GeoJSON.FeatureCollection {
  const features: GeoJSON.Feature[] = [];
  for (let lat = Math.ceil(south / step) * step; lat <= north; lat += step) {
    const coordinates = Array.from({ length: 361 }, (_, i) => [i - 180, lat]);
    features.push({
      type: "Feature",
      properties: {},
      geometry: { type: "LineString", coordinates },
    });
  }
  for (let lng = -180; lng < 180; lng += step) {
    const coordinates = Array.from({ length: north - south + 1 }, (_, i) => [lng, south + i]);
    features.push({
      type: "Feature",
      properties: {},
      geometry: { type: "LineString", coordinates },
    });
  }
  return { type: "FeatureCollection", features };
}

// NSIDC Sea Ice Polar Stereographic North: the North Pole in the middle,
// Greenland upright, no Mercator stretch.
// Register the CRS once, before any map whose style names it.
maplibregl.addProjection({
  name: "EPSG:3413",
  // The same string goes to proj4 in the workers, which project the GeoJSON below.
  definition: EPSG_3413,
  // forward([lng, lat]) gives [x, y] in meters, inverse goes back.
  projection: proj4(EPSG_4326, EPSG_3413),
  // The square tile grid GIBS serves EPSG:3413 in: top-left corner and width, in meters.
  tileMatrixSet: { origin: [-4194304, 4194304], extentAtZoom0: 8388608 },
});

// GeoJSON is cut into tiles in MapLibre's web workers, so they need proj4 too: projection-handler.mjs,
// below, builds the same converter there from the CRS's definition. Load it once, before the first map.
const workersReady = maplibregl.importScriptInWorkers(
  new URL("/projection-handler.mjs", location.href).href,
);

// Everything north of 66°, the Arctic Circle.
const bounds: maplibregl.LngLatBoundsLike = [
  [-180, 66],
  [180, 90],
];

export async function createMap(container: string | HTMLElement) {
  await workersReady;
  const map = new maplibregl.Map({
    container,
    style: {
      version: 8,
      projection: { type: "EPSG:3413" },
      glyphs: "https://tiles.openfreemap.org/fonts/{fontstack}/{range}.pbf",
      sources: {
        "blue-marble": {
          type: "raster",
          tiles: [gibs("BlueMarble_ShadedRelief_Bathymetry")],
          tileSize: 512,
          maxzoom: 6,
          attribution: 'Imagery: <a href="https://earthdata.nasa.gov/gibs">NASA GIBS</a>',
        },
        // Plain lng/lat GeoJSON, as on any other map.
        graticule: { type: "geojson", data: graticule(10, [30, 80]) },
        places: {
          type: "geojson",
          data: {
            type: "FeatureCollection",
            features: places.map(([name, lng, lat]) => ({
              type: "Feature",
              properties: { name },
              geometry: { type: "Point", coordinates: [lng, lat] },
            })),
          },
        },
      },
      layers: [
        { id: "blue-marble", type: "raster", source: "blue-marble" },
        {
          id: "graticule",
          type: "line",
          source: "graticule",
          paint: { "line-color": "#fff", "line-opacity": 0.35, "line-width": 1 },
        },
        {
          id: "places",
          type: "circle",
          source: "places",
          paint: {
            "circle-radius": 5,
            "circle-color": "#ff7a45",
            "circle-stroke-width": 2,
            "circle-stroke-color": "#fff",
          },
        },
        {
          id: "place-names",
          type: "symbol",
          source: "places",
          layout: {
            "text-field": ["get", "name"],
            "text-font": ["Noto Sans Bold"],
            "text-size": 13,
            "text-offset": [0, 1.2],
            "text-anchor": "top",
          },
          paint: {
            "text-color": "#fff",
            "text-halo-color": "rgba(0, 20, 40, 0.8)",
            "text-halo-width": 1.5,
          },
        },
      ],
    },
  });
  // Fit the box once the style has set the projection: the bounds option would fit it in Mercator.
  map.once("style.load", () => map.fitBounds(bounds, { padding: 16, animate: false }));
  return map;
}

projection-handler.mjs, a file next to the page that the code above loads into MapLibre's web workers with maplibregl.importScriptInWorkers. They cut GeoJSON into tiles, so they need proj4 too: it builds the converter there from the CRS's definition.

// Runs in MapLibre's web workers, which cut GeoJSON into tiles: it turns a CRS's
// `definition` into the same proj4 converter the page uses. Keep proj4's version in step with the page's.
import proj4 from "https://cdn.jsdelivr.net/npm/proj4@2.23.0/+esm";

self.setProjectionHandler((definition) => proj4(definition));

Countries in their national grid

National mapping agencies draw their maps in the grid their country is measured in. Where an agency publishes ready-made tiles (WMTS) the map uses them, as they load fastest; elsewhere its WMS draws each tile on request, through the {bbox} token. This page keeps the WMS tiles it shows in a cache of its own, so they come in at once; the code here asks the agencies directly.

Loading the map…

EPSG:3577 · GDA94 / Australian Albers

Australia, equal area

Geoscience Australia's base map, drawn by its ArcGIS server in Australian Albers, the equal-area projection for maps of the whole continent. {bbox} puts each tile's box in the export URL.

  • ArcGIS export with {bbox}
  • Equal area
Map code

Plain MapLibre GL JS 6.15 with proj4 and crs-defs, ready to paste into a module: createMap("map") makes the map in the element with the id map. With a bundler, point MapLibre at its worker first, as in the quick start.

import * as maplibregl from "maplibre-gl";
import "maplibre-gl/dist/maplibre-gl.css";
import proj4 from "proj4";
import { EPSG_4326, EPSG_3577 } from "crs-defs";

// GDA94 / Australian Albers, an equal-area projection for the whole continent.
// Register the CRS once, before any map whose style names it.
maplibregl.addProjection({
  name: "EPSG:3577",
  projection: proj4(EPSG_4326, EPSG_3577),
  // A square around Australia, 9,120 km wide. The server draws any box, so the grid is ours to pick.
  tileMatrixSet: { origin: [-4416000, 1539000], extentAtZoom0: 9120000 },
});

// The box the map opens on. Boxes are in lng/lat, whatever the projection.
const bounds: maplibregl.LngLatBoundsLike = [
  [112.9, -43.7],
  [153.7, -10.6],
];

export function createMap(container: string | HTMLElement) {
  const map = new maplibregl.Map({
    container,
    style: {
      version: 8,
      projection: { type: "EPSG:3577" },
      sources: {
        map: {
          type: "raster",
          // The export URL draws any box in any projection: {bbox} becomes each tile's box.
          tiles: [
            "https://services.ga.gov.au/gis/rest/services/NationalBaseMap/MapServer/export?bbox={bbox}&bboxSR=3577&imageSR=3577&size=512,512&format=png&f=image",
          ],
          tileSize: 512,
          maxzoom: 14,
          attribution: '© <a href="https://www.ga.gov.au/">Geoscience Australia</a>',
        },
      },
      layers: [{ id: "map", type: "raster", source: "map" }],
    },
  });
  // Fit the box once the style has set the projection: the bounds option would fit it in Mercator.
  map.once("style.load", () => map.fitBounds(bounds, { padding: 16, animate: false }));
  return map;
}

The world in any projection

A whole basemap of the world from Natural Earth's GeoJSON, with countries, rivers, lakes, cities and seas, projected in MapLibre's workers with proj4. Zoom in past level 5.5 for OpenStreetMap streets and buildings in the same projection, or write your own proj4 definition.

Edit the proj4 definition to draw your own. Keep +lon_0=0: the countries are cut at 180°, so another central meridian would stretch the ones that cross the new edge.

Loading the map…

  • A GeoJSON basemap
  • GeoJSON in the workers
  • OSM detail on zoom
  • Labels
  • Hover queries
  • Any proj4 projection
Map code

Plain MapLibre GL JS 6.15 with proj4 and crs-defs, ready to paste into a module: createMap("map") makes the map in the element with the id map. With a bundler, point MapLibre at its worker first, as in the quick start.

import * as maplibregl from "maplibre-gl";
import "maplibre-gl/dist/maplibre-gl.css";
import proj4 from "proj4";
import { EPSG_4326, EPSG_8857 } from "crs-defs";
// Natural Earth's 1:50m countries, borders, lakes, rivers, glaciers, cities and seas (public domain), in one
// file with a `kind` on each feature, and a point at least every degree. scripts/prepare-world-basemap.mjs makes it.
import basemapUrl from "./world-basemap.geojson?url";
// Closer in, OpenStreetMap from OpenFreeMap's vector tiles, as GeoJSON that MapLibre projects too.
import { addOsmDetail, MIN_ZOOM as OSM_ZOOM } from "./osm/detail";

/** The outline of the whole world: the ±180° meridians and the poles, a point every degree. */
const sphere: GeoJSON.Feature = {
  type: "Feature",
  properties: {},
  geometry: {
    type: "Polygon",
    coordinates: [
      [
        ...Array.from({ length: 181 }, (_, i): [number, number] => [-180, -90 + i]),
        ...Array.from({ length: 361 }, (_, i): [number, number] => [-180 + i, 90]),
        ...Array.from({ length: 181 }, (_, i): [number, number] => [180, 90 - i]),
        ...Array.from({ length: 361 }, (_, i): [number, number] => [180 - i, -90]),
      ],
    ],
  },
};

/** Lines of latitude and longitude as GeoJSON, with a point every degree so they curve with the projection. */
function graticule(step = 10, latRange: [number, number] = [-80, 80]): GeoJSON.FeatureCollection {
  const features: GeoJSON.Feature[] = [];
  const line = (coordinates: [number, number][]) =>
    features.push({
      type: "Feature",
      properties: {},
      geometry: { type: "LineString", coordinates },
    });
  const [south, north] = latRange;
  for (let lat = Math.ceil(south / step) * step; lat <= north; lat += step) {
    line(Array.from({ length: 361 }, (_, i) => [i - 180, lat]));
  }
  for (let lng = -180; lng < 180; lng += step) {
    line(Array.from({ length: north - south + 1 }, (_, i) => [lng, south + i]));
  }
  return { type: "FeatureCollection", features };
}

/** The smallest square grid that holds the whole world, found by projecting a lng/lat grid of points. */
function worldSquare(projection: { forward(p: number[]): number[] }) {
  let [minX, minY, maxX, maxY] = [Infinity, Infinity, -Infinity, -Infinity];
  for (let lng = -180; lng <= 180; lng += 2) {
    for (let lat = -90; lat <= 90; lat += 2) {
      const [x, y] = projection.forward([lng, lat]);
      if (!Number.isFinite(x) || !Number.isFinite(y)) {
        throw new Error(
          "That projection can't show the whole world: places like the far side of an orthographic globe have no position in it.",
        );
      }
      [minX, minY, maxX, maxY] = [
        Math.min(minX, x),
        Math.min(minY, y),
        Math.max(maxX, x),
        Math.max(maxY, y),
      ];
    }
  }
  const side = Math.max(maxX - minX, maxY - minY) * 1.04;
  const origin: [number, number] = [(minX + maxX - side) / 2, (minY + maxY + side) / 2];
  return { origin, extentAtZoom0: side };
}

/** The basemap's colors, in the site's light and dark themes. */
const LIGHT = {
  water: "#cfe1f2",
  graticule: "#b3cbe3",
  land: ["#f3e3c3", "#e3ebc6", "#f1d6cb", "#d4e8d6", "#e9dbe9", "#f6ecc8", "#dedaf0"],
  ice: "#fbfdff",
  river: "#9ec0e4",
  border: "#8a8075",
  sea: "#56789f",
  city: "#3d3a36",
  text: "#2f2b27",
  country: "#5f554b",
  halo: "rgba(255, 255, 255, 0.85)",
};
const DARK = {
  water: "#15223a",
  graticule: "#253656",
  land: ["#3a3a46", "#343f3a", "#423a40", "#323f47", "#3d3848", "#433f35", "#373a4d"],
  ice: "#56657a",
  river: "#355f8f",
  border: "#8792a8",
  sea: "#7ea3d1",
  city: "#dfe4ee",
  text: "#e6e9f0",
  country: "#c4cad6",
  halo: "rgba(15, 23, 42, 0.85)",
};

// GeoJSON is cut into tiles in MapLibre's web workers, so they need proj4 too: projection-handler.mjs,
// below, builds the same converter there from the CRS's definition. Load it once, before the first map.
const workersReady = maplibregl.importScriptInWorkers(
  new URL("/projection-handler.mjs", location.href).href,
);

/** A world map in any proj4 projection. Every one gets its own name, since a name is registered once. */
let count = 0;
export async function createMap(
  container: string | HTMLElement,
  { definition = EPSG_8857, dark = false } = {},
) {
  let projection;
  try {
    projection = proj4(EPSG_4326, definition);
  } catch {
    throw new Error(
      "proj4 couldn't read that definition. github.com/birkskyum/crs-defs has the proj4 string of every EPSG and ESRI code.",
    );
  }
  const tileMatrixSet = worldSquare(projection);
  // Dragging and zooming convert screen points back to lng/lat, so the inverse has to work too.
  for (const lngLat of [
    [0, 0],
    [100, 40],
    [-60, -30],
  ]) {
    if (!projection.inverse(projection.forward(lngLat)).every(Number.isFinite)) {
      throw new Error(
        "proj4 can't convert back from that projection, and the map needs that to pan and zoom.",
      );
    }
  }
  const name = `custom:world-${++count}`;
  maplibregl.addProjection({
    name,
    // The same string goes to proj4 in the workers, which project the GeoJSON below.
    definition,
    // proj4 straight in: past the world's edge, where it wraps positions around, MapLibre stops at the edge.
    projection,
    tileMatrixSet,
  });
  await workersReady;

  const c = dark ? DARK : LIGHT;
  const kind = (name: string) => ["==", ["get", "kind"], name] as ["==", ["get", "kind"], string];
  const map = new maplibregl.Map({
    container,
    style: {
      version: 8,
      projection: { type: name },
      glyphs: "https://tiles.openfreemap.org/fonts/{fontstack}/{range}.pbf",
      sources: {
        sphere: { type: "geojson", data: sphere },
        graticule: { type: "geojson", data: graticule(15, [-90, 90]) },
        basemap: {
          type: "geojson",
          data: basemapUrl,
          attribution: 'Made with <a href="https://www.naturalearthdata.com/">Natural Earth</a>',
        },
      },
      layers: [
        { id: "ocean", type: "fill", source: "sphere", paint: { "fill-color": c.water } },
        {
          id: "graticule",
          type: "line",
          source: "graticule",
          paint: { "line-color": c.graticule, "line-width": 0.6 },
        },
        {
          id: "countries",
          type: "fill",
          source: "basemap",
          filter: kind("country"),
          // Natural Earth's 7-color scheme: neighbors never share a color.
          paint: {
            "fill-color": [
              "match",
              ["get", "color"],
              1,
              c.land[0],
              2,
              c.land[1],
              3,
              c.land[2],
              4,
              c.land[3],
              5,
              c.land[4],
              6,
              c.land[5],
              c.land[6],
            ],
          },
        },
        {
          id: "glaciers",
          type: "fill",
          source: "basemap",
          filter: kind("glacier"),
          paint: { "fill-color": c.ice },
        },
        {
          id: "lakes",
          type: "fill",
          source: "basemap",
          filter: kind("lake"),
          paint: { "fill-color": c.water },
        },
        {
          id: "rivers",
          type: "line",
          source: "basemap",
          // Rivers by rank, 1 the biggest: the main ones from the start, the rest as the map zooms in.
          filter: ["all", kind("river"), ["<=", ["get", "rank"], ["+", ["zoom"], 2]]],
          layout: { "line-cap": "round", "line-join": "round" },
          paint: {
            "line-color": c.river,
            "line-width": [
              "interpolate",
              ["linear"],
              ["zoom"],
              0,
              ["max", 0.3, ["-", 1.4, ["*", 0.12, ["get", "rank"]]]],
              5,
              ["max", 0.6, ["-", 3, ["*", 0.2, ["get", "rank"]]]],
            ],
          },
        },
        {
          id: "state-borders",
          maxzoom: OSM_ZOOM,
          type: "line",
          source: "basemap",
          filter: kind("state-border"),
          minzoom: 1.5,
          paint: {
            "line-color": c.border,
            "line-opacity": 0.45,
            "line-width": 0.5,
            "line-dasharray": [3, 2],
          },
        },
        {
          id: "borders",
          maxzoom: OSM_ZOOM,
          type: "line",
          source: "basemap",
          filter: ["all", kind("border"), ["!", ["get", "disputed"]]],
          layout: { "line-join": "round" },
          paint: {
            "line-color": c.border,
            "line-width": ["interpolate", ["linear"], ["zoom"], 0, 0.5, 5, 1.4],
          },
        },
        {
          id: "disputed-borders",
          maxzoom: OSM_ZOOM,
          type: "line",
          source: "basemap",
          filter: ["all", kind("border"), ["get", "disputed"]],
          paint: { "line-color": c.border, "line-width": 0.8, "line-dasharray": [2, 2] },
        },
        {
          id: "sea-labels",
          maxzoom: OSM_ZOOM,
          type: "symbol",
          source: "basemap",
          // Oceans first; seas and gulfs as the map zooms in to them.
          filter: ["all", kind("sea-label"), ["<=", ["get", "rank"], ["+", ["zoom"], 1.5]]],
          layout: {
            "text-field": ["get", "name"],
            "text-font": ["Noto Sans Italic"],
            "text-size": ["case", ["get", "ocean"], 14, 11],
            "text-letter-spacing": ["case", ["get", "ocean"], 0.3, 0.1],
            "text-max-width": 6,
            "symbol-sort-key": ["get", "rank"],
          },
          paint: { "text-color": c.sea, "text-halo-color": c.water, "text-halo-width": 1 },
        },
        {
          id: "city-dots",
          maxzoom: OSM_ZOOM,
          type: "circle",
          source: "basemap",
          filter: ["all", kind("city"), ["<=", ["get", "rank"], ["+", ["zoom"], 1.2]]],
          paint: {
            "circle-radius": ["case", ["get", "capital"], 3, 2],
            "circle-color": c.city,
            "circle-stroke-color": c.halo,
            "circle-stroke-width": 1,
          },
        },
        {
          id: "city-labels",
          maxzoom: OSM_ZOOM,
          type: "symbol",
          source: "basemap",
          filter: ["all", kind("city"), ["<=", ["get", "rank"], ["+", ["zoom"], 1.2]]],
          layout: {
            "text-field": ["get", "name"],
            "text-font": [
              "case",
              ["get", "capital"],
              ["literal", ["Noto Sans Bold"]],
              ["literal", ["Noto Sans Regular"]],
            ],
            "text-size": ["case", ["get", "capital"], 12, 11],
            "text-variable-anchor": ["left", "right", "top", "bottom"],
            "text-radial-offset": 0.5,
            "symbol-sort-key": ["get", "rank"],
          },
          paint: { "text-color": c.text, "text-halo-color": c.halo, "text-halo-width": 1.2 },
        },
        {
          id: "country-labels",
          maxzoom: OSM_ZOOM,
          type: "symbol",
          source: "basemap",
          // Big countries from the start, smaller ones as the map zooms in.
          filter: ["all", kind("country-label"), ["<=", ["get", "rank"], ["+", ["zoom"], 2.5]]],
          layout: {
            "text-field": ["get", "name"],
            "text-font": ["Noto Sans Bold"],
            "text-size": ["interpolate", ["linear"], ["zoom"], 0, 9, 4, 13],
            "text-transform": "uppercase",
            "text-letter-spacing": 0.12,
            "text-max-width": 7,
            "symbol-sort-key": ["get", "rank"],
          },
          paint: { "text-color": c.country, "text-halo-color": c.halo, "text-halo-width": 1.2 },
        },
      ],
    },
    maxZoom: 16,
  });
  // Fit the whole world once the style has set the projection: the bounds option would fit it in Mercator.
  map.once("style.load", () => {
    map.fitBounds(
      [
        [-180, -90],
        [180, 90],
      ],
      { padding: 16, animate: false },
    );
    addOsmDetail(map, dark).catch(console.error);
  });

  // Queries return lng/lat and the source's own properties, as on any map.
  const popup = new maplibregl.Popup({ closeButton: false, closeOnClick: false });
  map.on("mousemove", "countries", (e) => {
    if (map.getZoom() >= OSM_ZOOM) {
      popup.remove();
      return;
    }
    popup.setLngLat(e.lngLat).setText(String(e.features?.[0]?.properties.name)).addTo(map);
  });
  map.on("mouseleave", "countries", () => popup.remove());
  return map;
}

projection-handler.mjs, a file next to the page that the code above loads into MapLibre's web workers with maplibregl.importScriptInWorkers. They cut GeoJSON into tiles, so they need proj4 too: it builds the converter there from the CRS's definition.

// Runs in MapLibre's web workers, which cut GeoJSON into tiles: it turns a CRS's
// `definition` into the same proj4 converter the page uses. Keep proj4's version in step with the page's.
import proj4 from "https://cdn.jsdelivr.net/npm/proj4@2.23.0/+esm";

self.setProjectionHandler((definition) => proj4(definition));

osm/detail.ts fetches OpenFreeMap's Liberty (or Dark) style and streams visible vector tiles into a GeoJSON source past zoom 5.5 via updateData().

// OpenStreetMap detail for the world map on /projections/, in any projection. OpenFreeMap's vector tiles are
// cut in the Web Mercator grid, which a registered projection can't use, so past zoom MIN_ZOOM the tiles under
// the view are turned into GeoJSON in lng/lat (tiles.worker.ts), and MapLibre projects that in its workers, as
// it does any GeoJSON. OpenFreeMap's own style (Liberty, or Dark in the site's dark theme) draws it.
import type {
  FilterSpecification,
  GeoJSONSource,
  LayerSpecification,
  Map,
  StyleSpecification,
} from "maplibre-gl";
import TilesWorker from "./tiles.worker.ts?worker";
import type { TileAnswer, TileRequest } from "./tiles.worker";

/** The map zoom from which OpenStreetMap shows, where Natural Earth's 1:50m runs out of detail. */
export const MIN_ZOOM = 5.5;
/** OpenFreeMap's deepest tiles; closer in, the map keeps showing them larger. */
const MAX_TILE_ZOOM = 14;
/** At most this many tiles at once, so the GeoJSON stays small enough to project quickly. */
const MAX_TILES = 12;
const EARTH_CIRCUMFERENCE = 40075016.686;

const STYLES = {
  light: "https://tiles.openfreemap.org/styles/liberty",
  dark: "https://tiles.openfreemap.org/styles/dark",
};

/** Adds OpenStreetMap detail to a map of the world in any projection, streaming tiles incrementally. */
export async function addOsmDetail(map: Map, dark: boolean) {
  let removed = false;
  map.on("remove", () => (removed = true));

  const style: StyleSpecification = await (await fetch(dark ? STYLES.dark : STYLES.light)).json();
  const vector = style.sources.openmaptiles;
  if (vector?.type !== "vector" || !vector.url)
    throw new Error("OpenFreeMap's style has no openmaptiles source");
  const tileJson: { tiles: string[]; attribution?: string } = await (
    await fetch(vector.url)
  ).json();
  const template = tileJson.tiles[0];
  if (removed || !map.getStyle()) return;

  if (typeof style.sprite === "string") map.setSprite(style.sprite);
  map.addSource("osm", {
    type: "geojson",
    data: { type: "FeatureCollection", features: [] },
    ...(tileJson.attribution && { attribution: tileJson.attribution }),
  });
  const background = style.layers.find((layer) => layer.type === "background");
  const land = background?.paint?.["background-color"] ?? "#f8f4f0";
  map.addLayer({
    id: "osm-land",
    type: "fill",
    source: "osm",
    minzoom: MIN_ZOOM,
    filter: ["==", ["get", "_layer"], "_tile"],
    // Tiles meet edge to edge: smoothing their edges would let a hairline of what's below show between them.
    paint: { "fill-color": land as string, "fill-antialias": false },
  });
  /** The zoom from which the style draws each of the tiles' layers. */
  const fromZoom = new globalThis.Map<string, number>();
  for (const layer of style.layers) {
    if (!("source-layer" in layer) || layer.source !== "openmaptiles") continue;
    const { "source-layer": sourceLayer, ...rest } = layer as typeof layer & {
      "source-layer": string;
    };
    fromZoom.set(sourceLayer, Math.min(fromZoom.get(sourceLayer) ?? Infinity, layer.minzoom ?? 0));
    // Polygons are cut at their tile's edges, so an outline would trace the cuts.
    if (rest.type === "fill" && rest.paint) delete rest.paint["fill-outline-color"];
    const ofLayer: FilterSpecification = ["==", ["get", "_layer"], sourceLayer];
    map.addLayer({
      ...rest,
      id: `osm-${layer.id}`,
      source: "osm",
      minzoom: Math.max(layer.minzoom ?? 0, MIN_ZOOM),
      filter: layer.filter ? ["all", ofLayer, layer.filter as FilterSpecification] : ofLayer,
    } as LayerSpecification);
  }

  const worker = new TilesWorker();
  /** Feature IDs currently loaded into MapLibre's GeoJSON source, keyed by tile key. */
  const inSource = new globalThis.Map<string, string[]>();
  /** Tile keys currently in flight in the worker. */
  const pending = new Set<string>();
  let wantedKeys = new Set<string>();
  let request = 0;

  worker.onmessage = (event: MessageEvent<{ id: number; answer: TileAnswer }>) => {
    const { answer } = event.data;
    pending.delete(answer.key);
    if (removed || !wantedKeys.has(answer.key) || inSource.has(answer.key)) return;
    if (answer.failed) return;
    const ids = answer.features.map((feature) => String(feature.id));
    inSource.set(answer.key, ids);
    if (answer.features.length) {
      const source = map.getSource<GeoJSONSource>("osm");
      void source?.updateData({ add: answer.features });
    }
  };

  function update() {
    const source = map.getSource<GeoJSONSource>("osm");
    if (map.getZoom() < MIN_ZOOM) {
      wantedKeys = new Set();
      pending.clear();
      if (inSource.size) {
        inSource.clear();
        void source?.updateData({ removeAll: true });
      }
      return;
    }
    // Only the layers the style draws at this zoom: buildings, for one, are most of a city's data.
    const layers = [...fromZoom]
      .filter(([, zoom]) => zoom <= map.getZoom() + 0.5)
      .map(([name]) => name);
    const wanted = tilesInView(map, template, layers);
    wantedKeys = new Set(wanted.map((tile) => tile.key));

    // Drop tiles that left the view so memory stays bounded and pans only push the diff.
    const staleKeys = [...inSource.keys()].filter((key) => !wantedKeys.has(key));
    if (staleKeys.length === inSource.size && inSource.size > 0) {
      inSource.clear();
      void source?.updateData({ removeAll: true });
    } else if (staleKeys.length) {
      const remove: string[] = [];
      for (const key of staleKeys) {
        remove.push(...(inSource.get(key) ?? []));
        inSource.delete(key);
      }
      if (remove.length) void source?.updateData({ remove });
    }

    const missing = wanted.filter((tile) => !inSource.has(tile.key) && !pending.has(tile.key));
    if (missing.length) {
      for (const tile of missing) pending.add(tile.key);
      worker.postMessage({ id: ++request, tiles: missing });
    }
  }

  map.on("moveend", update);
  map.on("remove", () => worker.terminate());
  update();
}

/**
 * The Web Mercator tiles under the map's view, at the zoom whose resolution matches the map's at its center.
 * The view's lng/lat box comes from points across the screen, since a projection's view is no lng/lat box.
 */
function tilesInView(map: Map, template: string, layers: string[]): TileRequest[] {
  const { width, height } = map.getContainer().getBoundingClientRect();
  const lngLats = [];
  for (let i = 0; i <= 8; i++) {
    for (let j = 0; j <= 8; j++) lngLats.push(map.unproject([(width * i) / 8, (height * j) / 8]));
  }
  const west = Math.max(-180, Math.min(...lngLats.map((p) => p.lng)));
  const east = Math.min(180, Math.max(...lngLats.map((p) => p.lng)));
  const south = Math.max(-85, Math.min(...lngLats.map((p) => p.lat)));
  const north = Math.min(85, Math.max(...lngLats.map((p) => p.lat)));

  const center = map.unproject([width / 2, height / 2]);
  const metersPerPixel = map.unproject([width / 2 + 1, height / 2]).distanceTo(center);
  const latitude = Math.max(-85, Math.min(85, center.lat));
  let z = Math.round(
    Math.log2(
      (EARTH_CIRCUMFERENCE * Math.cos((latitude * Math.PI) / 180)) / (512 * metersPerPixel),
    ),
  );
  z = Math.max(0, Math.min(MAX_TILE_ZOOM, z));
  for (;;) {
    const [x0, y0] = tileOf(west, north, z);
    const [x1, y1] = tileOf(east, south, z);
    const count = (x1 - x0 + 1) * (y1 - y0 + 1);
    if (count <= MAX_TILES || z === 0) {
      const tiles: TileRequest[] = [];
      for (let x = x0; x <= x1; x++) {
        for (let y = y0; y <= y1; y++) {
          const url = template
            .replace("{z}", String(z))
            .replace("{x}", String(x))
            .replace("{y}", String(y));
          tiles.push({ key: `${z}/${x}/${y}/${layers.join(",")}`, url, z, x, y, layers });
        }
      }
      return tiles;
    }
    z--;
  }
}

function tileOf(lng: number, lat: number, z: number): [number, number] {
  const n = 2 ** z;
  const x = Math.min(n - 1, Math.max(0, Math.floor(((lng + 180) / 360) * n)));
  const sin = Math.sin((lat * Math.PI) / 180);
  const y = Math.min(
    n - 1,
    Math.max(0, Math.floor((0.5 - Math.log((1 + sin) / (1 - sin)) / (4 * Math.PI)) * n)),
  );
  return [x, y];
}

osm/tiles.worker.ts decodes each vector tile with @mapbox/vector-tile, clips features cleanly to tile boundaries, and returns lng/lat GeoJSON features for MapLibre's workers to project.

// Turns OpenFreeMap's vector tiles, cut in the Web Mercator grid, into GeoJSON in lng/lat, which MapLibre
// projects into any CRS in its own workers. Each tile's features are clipped to the tile's own edges, so
// neighboring tiles meet without overlapping and a label isn't drawn twice. Each tile is posted back as
// soon as it decodes, with stable per-tile feature IDs so the main thread can stream it into the source
// incrementally via updateData().
import { VectorTile, classifyRings } from "@mapbox/vector-tile";
import { PbfReader } from "pbf";

export interface TileRequest {
  key: string;
  url: string;
  z: number;
  x: number;
  y: number;
  /** The tile's layers the style draws at the map's zoom; the rest are left out. */
  layers: string[];
}
export interface TileAnswer {
  key: string;
  features: GeoJSON.Feature[];
  failed?: boolean;
}

type XY = [number, number];

/**
 * How far polygons reach past their tile's edge, in tile units (4,096 to a tile): about a pixel, so that
 * neighboring pieces overlap and their smoothed edges don't leave a hairline between them.
 */
const POLYGON_OVERLAP = 8;

/** House numbers are too many for GeoJSON in a browser, and Liberty only shows them up close. */
const SKIPPED_LAYERS = new Set(["housenumber"]);

self.onmessage = (event: MessageEvent<{ id: number; tiles: TileRequest[] }>) => {
  const { id, tiles } = event.data;
  for (const tile of tiles) {
    void decode(tile).then((answer) => self.postMessage({ id, answer }));
  }
};

async function decode(request: TileRequest): Promise<TileAnswer> {
  try {
    const response = await fetch(request.url);
    if (!response.ok) return { key: request.key, features: [], failed: response.status !== 404 };
    const tile = new VectorTile(new PbfReader(new Uint8Array(await response.arrayBuffer())));
    return { key: request.key, features: features(tile, request) };
  } catch {
    return { key: request.key, features: [], failed: true };
  }
}

function features(tile: VectorTile, { key, z, x, y, layers }: TileRequest): GeoJSON.Feature[] {
  let seq = 0;
  const out: GeoJSON.Feature[] = [tileOutline(key, z, x, y, seq++)];
  for (const name of Object.keys(tile.layers)) {
    if (SKIPPED_LAYERS.has(name) || !layers.includes(name)) continue;
    const layer = tile.layers[name];
    const toLngLat = lngLatOf(z, x, y, layer.extent);
    for (let i = 0; i < layer.length; i++) {
      const feature = layer.feature(i);
      const points = feature.loadGeometry();
      // Polygons come as rings: group them into outer rings with their holes first.
      const parts = feature.type === 3 ? classifyRings(points) : [points];
      const xy = parts.map((part) => part.map((ring) => ring.map((p): XY => [p.x, p.y])));
      const geometry = clipped(feature.type, xy, layer.extent, toLngLat);
      if (!geometry) continue;
      out.push({
        type: "Feature",
        id: `${key}#${seq++}`,
        properties: { ...feature.properties, _layer: name },
        geometry,
      });
    }
  }
  return out;
}

/** The tile's own square, for the land color under its features, with points along its edges so it curves. */
function tileOutline(key: string, z: number, x: number, y: number, seq: number): GeoJSON.Feature {
  const toLngLat = lngLatOf(z, x, y, 1);
  const ring: XY[] = [];
  const steps = 16;
  for (let i = 0; i < steps; i++) ring.push(toLngLat([i / steps, 0]));
  for (let i = 0; i < steps; i++) ring.push(toLngLat([1, i / steps]));
  for (let i = 0; i < steps; i++) ring.push(toLngLat([1 - i / steps, 1]));
  for (let i = 0; i < steps; i++) ring.push(toLngLat([0, 1 - i / steps]));
  ring.push(ring[0]);
  return {
    type: "Feature",
    id: `${key}#${seq}`,
    properties: { _layer: "_tile" },
    geometry: { type: "Polygon", coordinates: [ring] },
  };
}

/** From a tile's own coordinates, 0 to extent from its top-left corner, to lng/lat with six decimals. */
function lngLatOf(z: number, x: number, y: number, extent: number) {
  const tiles = 2 ** z;
  return ([px, py]: XY): XY => {
    const lng = ((x + px / extent) / tiles) * 360 - 180;
    const mercatorY = Math.PI * (1 - (2 * (y + py / extent)) / tiles);
    const lat = (Math.atan(Math.sinh(mercatorY)) * 180) / Math.PI;
    return [Math.round(lng * 1e6) / 1e6, Math.round(lat * 1e6) / 1e6];
  };
}

/** The feature cut to the tile's square, in lng/lat; parts are polygons for type 3, else one list of lines or points. */
function clipped(
  type: number,
  parts: XY[][][],
  extent: number,
  toLngLat: (p: XY) => XY,
): GeoJSON.Geometry | null {
  if (type === 1) {
    const points = parts[0]
      .flat()
      .filter(([px, py]) => px >= 0 && px < extent && py >= 0 && py < extent);
    if (!points.length) return null;
    return points.length === 1
      ? { type: "Point", coordinates: toLngLat(points[0]) }
      : { type: "MultiPoint", coordinates: points.map(toLngLat) };
  }
  if (type === 2) {
    const lines = parts[0]
      .flatMap((line) => clipLine(line, extent))
      .filter((line) => line.length > 1);
    if (!lines.length) return null;
    return { type: "MultiLineString", coordinates: lines.map((line) => line.map(toLngLat)) };
  }
  if (type === 3) {
    const polygons = parts.flatMap((polygon) => {
      const [outer, ...holes] = polygon.map((ring) =>
        clipRing(ring, -POLYGON_OVERLAP, extent + POLYGON_OVERLAP),
      );
      // Nothing of the outer ring inside the tile, nothing of the polygon.
      if (!outer || outer.length < 4) return [];
      return [[outer, ...holes.filter((ring) => ring.length >= 4)]];
    });
    if (!polygons.length) return null;
    return {
      type: "MultiPolygon",
      coordinates: polygons.map((polygon) => polygon.map((ring) => ring.map(toLngLat))),
    };
  }
  return null;
}

/** A line cut to the square 0..extent, as the pieces inside it. */
function clipLine(line: XY[], extent: number): XY[][] {
  const pieces: XY[][] = [];
  let current: XY[] = [];
  for (let i = 1; i < line.length; i++) {
    const segment = clipSegment(line[i - 1], line[i], extent);
    if (!segment) {
      if (current.length) pieces.push(current);
      current = [];
      continue;
    }
    const [a, b] = segment;
    const last = current[current.length - 1];
    if (!last || last[0] !== a[0] || last[1] !== a[1]) {
      if (current.length) pieces.push(current);
      current = [a];
    }
    current.push(b);
  }
  if (current.length) pieces.push(current);
  return pieces;
}

/** Liang-Barsky: the part of the segment inside the square, or null. */
function clipSegment([x0, y0]: XY, [x1, y1]: XY, extent: number): [XY, XY] | null {
  let t0 = 0;
  let t1 = 1;
  const dx = x1 - x0;
  const dy = y1 - y0;
  for (const [p, q] of [
    [-dx, x0],
    [dx, extent - x0],
    [-dy, y0],
    [dy, extent - y0],
  ]) {
    if (p === 0) {
      if (q < 0) return null;
      continue;
    }
    const t = q / p;
    if (p < 0) {
      if (t > t1) return null;
      t0 = Math.max(t0, t);
    } else {
      if (t < t0) return null;
      t1 = Math.min(t1, t);
    }
  }
  return [
    [x0 + t0 * dx, y0 + t0 * dy],
    [x0 + t1 * dx, y0 + t1 * dy],
  ];
}

/** Sutherland-Hodgman: the ring cut to the square min..max, closed. */
function clipRing(ring: XY[], min: number, max: number): XY[] {
  let points = ring;
  for (const [axis, bound, keepBelow] of [
    [0, min, false],
    [0, max, true],
    [1, min, false],
    [1, max, true],
  ] as const) {
    const inside = (p: XY) => (keepBelow ? p[axis] <= bound : p[axis] >= bound);
    const cross = (a: XY, b: XY): XY => {
      const t = (bound - a[axis]) / (b[axis] - a[axis]);
      return [a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])];
    };
    const next: XY[] = [];
    for (let i = 0; i < points.length; i++) {
      const current = points[i];
      const previous = points[(i + points.length - 1) % points.length];
      if (inside(current)) {
        if (!inside(previous)) next.push(cross(previous, current));
        next.push(current);
      } else if (inside(previous)) {
        next.push(cross(previous, current));
      }
    }
    points = next;
    if (!points.length) return [];
  }
  if (
    points[0][0] !== points[points.length - 1][0] ||
    points[0][1] !== points[points.length - 1][1]
  ) {
    points.push(points[0]);
  }
  return points;
}

How it works

A map in a custom coordinate reference system (CRS) takes three things.

  1. Step 1

    Describe the grid

    Register the CRS once with maplibregl.addProjection: a name, a converter from lng/lat to its coordinates (proj4 makes one from any definition), and the tile grid's top-left corner and width.

  2. Step 2

    Load tiles made in it

    Raster and vector tiles, WMTS and WMS (with the {bbox} token), DEM, image and video sources: anything served in the CRS's square grid. The map positions the tiles, it doesn't reproject them.

  3. Step 3

    Keep using lng/lat

    Markers, popups, fitBounds, flyTo, project, queryRenderedFeatures and GeoJSON all work in lng/lat, as on a Mercator map. The map converts through the CRS.

Good to know

  • It's experimental, so the API can still change in a minor release.
  • Tiles must be made in the CRS. Web Mercator tiles aren't reprojected, so a Mercator basemap won't line up.
  • One CRS per map, flat: no globe and no world copies.
  • The grid must be a square quad tree, where each zoom level splits every tile in four.
  • Pick the projection in the style before the sources load. To switch, make a new map, as this page does.

Go further