Skip to content
Documentation menu
docs / sdks · raw .md

SDKs & installation

Five SDKs over one Rust core, plus a point-cloud renderer, a voice guidance phrasebook (beta), a territory command-line tool and a GeoJSON tiler. The mobile packages ship from tagged releases (sdk-v*); the npm packages can also be cut on their own between tags, so their versions run ahead. Fleet customers licence the on-device SDK per vehicle; app developers can meter per monthly active user instead (see pricing).

Status: the npm packages are live: @mapmap/maps, @mapmap/points, @mapmap/core, @mapmap/react-native, @mapmap/voice (beta), @mapmap/territory and @mapmap/tile install from npm today. The iOS package installs publicly via Swift Package Manager from the distribution repository Mapmapai/mapmap-ios (current release 0.9.0). The Android AAR publishes to Maven Central (current release 0.9.0), which needs no account and no token. The zero-install way in is the playground; the hosted gateway at https://api.mapmap.ai is live (sign up for a key), and the same gateway runs from the self-host distro; base URL, auth and quotas are defined in conventions.

Compatibility

SDKPackageVersionPlatform floorPeer requirements
Web maps@mapmap/maps0.25.2Node ≥ 18 to build; ESM onlymaplibre-gl ≥ 5 < 7, pmtiles ≥ 3 < 5; optional: three ≥ 0.167 < 1 and 3d-tiles-renderer ^0.5.3 (3D models and 3D Tiles only)
Point clouds@mapmap/points0.6.0Node ≥ 18 to build; ESM only; WebGL 2maplibre-gl ≥ 5.6 < 6 or ≥ 6.9 < 7, three ≥ 0.160 < 1, laz-perf ^0.0.7 optional (COPC only)
Core (WASM)@mapmap/core0.4.0Node and browser builds in one package (exports picks by environment)none
React Native@mapmap/react-native0.5.0iOS 16.4, minSdk 26; Expo SDK 52+, or bare React Native 0.74+expo-modules-core, react, react-native; expo ≥ 52 optional. Pulls MapMapKit ~> 0.9.0 (CocoaPods) and ai.mapmap:core (Maven Central)
Voice guidance (beta)@mapmap/voice0.1.0-beta.1Node ≥ 18; no DOM, no Node built-ins, runs on Hermesnone, and no runtime dependencies
Territory CLI@mapmap/territory0.1.1Node ≥ 20.19 (full content verification needs Node 22.15+ or a zstd binary)none
Tiling@mapmap/tile0.1.0Node ≥ 18 (command line, ES module or require); browsers with WebAssemblynone, and no runtime dependencies
Androidai.mapmap:core0.9.0minSdk 26, JDK 17 to buildnone
iOSMapMapKit (Mapmapai/mapmap-ios)0.9.0iOS 16.4, Swift tools 5.9none

Versions checked on 5 November 2026: the npm rows with npm view <package> version peerDependencies engines, Android against Maven Central's ai/mapmap/core/maven-metadata.xml, and iOS against the Mapmapai/mapmap-ios releases. The Android, iOS and React Native rows moved on 8 November 2026 with the 0.9.0 release (0.9.0, 0.9.0 and 0.5.0).

iOS: never pin 0.2.0. The 0.2.0 iOS release shipped without its generated Swift bindings and did not compile; 0.2.1 is the packaging fix (same checksum-pinned binary core).

Web maps: @mapmap/maps

Availability: live on npm.

A thin TypeScript wrapper over MapLibre GL JS that gives you a MapMap map with our tiles, styles and routing wired in. You need an snk_ API key; issue one card-free in the quickstart.

bash
npm install @mapmap/maps maplibre-gl pmtiles

Under Vite or Turbopack, also serve MapLibre's worker from your app, or the map stays blank: two files and one call.

The map needs MapLibre's stylesheet and a container with a real height:

html
<div id="map" style="height: 480px"></div>

The example below routes a hazmat truck. ADR (the European agreement on carriage of dangerous goods by road; tunnel codes B–E restrict which tunnels a hazmat load may use) is a first-class routing parameter; the full tunnel-code table is in conventions.

ts
import "maplibre-gl/dist/maplibre-gl.css";
import { createMap, RouteLayer } from "@mapmap/maps";

const map = createMap({
  container: "map",
  apiKey: "snk_...", // from the quickstart
  // baseUrl defaults to https://api.mapmap.ai
});
await map.whenReady();

const routes = new RouteLayer(map);
const route = await routes.route(
  { lon: -0.1278, lat: 51.5074 }, // London
  { lon: -1.8904, lat: 52.4862 }, // Birmingham
  { profile: "truck", truck: { heightM: 4.0, weightT: 40, hazmat: true, tunnelCode: "C" } },
);

route.distanceM; // total distance, metres
route.durationS; // total duration, seconds
route.geometry;  // GeoJSON LineString ([lng, lat] positions), already drawn on the map
route.raw;       // the raw routes[0] object, for leg/step detail

Alternatives, ferry legs and geometry you already hold

Offering a choice of routes is table stakes for a navigation UI, so RouteLayer draws the unselected ones dimmer and beneath, clickable to switch. The selected route keeps everything else the layer does: progress, manoeuvre arrow, alert corridors.

ts
routes.drawAlternatives(parsedRoutes, selectedIndex);
routes.onSelectAlternative((i) => routes.drawAlternatives(parsedRoutes, i));

// Ferry legs as dashes over the selected line, so a water crossing does
// not read as driving. Supplied explicitly, because line-dasharray cannot
// be data-driven and only you know which legs are ferries.
routes.setFerrySegments([[[lng, lat], ...]]);

// A line you already have, with no ParsedRoute to build:
routes.drawGeometry([[lng, lat], ...]);

// Runtime paint over the design, e.g. marking a route provisional or
// straight-line-approximated. Survives style reloads; `{}` clears it.
routes.setLineStyle({ color: "#9096a2", dash: [1.6, 1.4], casingOpacity: 0 });
Multi-stop routing drawn live with RouteLayer · © OpenStreetMap contributors © OpenMapTiles

Coordinates are accepted as [lng, lat] arrays, { lng, lat } or { lon, lat } objects. Profiles: driving (the default), walking and truck; the truck options (heightM, widthM, lengthM, weightT, hazmat, tunnelCode) only apply to the truck profile. AdrCheck (a typed client for the gateway's POST /adr/check compliance endpoint) and the pmtiles protocol are wired up for you.

Label language is a style option: buildStyle({ labelLanguage: "ja" }) renders labels in that language with local-name fallback ("local" shows every place in its own language); see label languages. PlacesLayer renders your own places (pins, clustering, popups, on-map labels, a different icon per place, nearest by straight line or by drive time) and pairs with the hosted /places store-finder API. MarkersLayer draws the markers a designer placed in Studio's Markers section and shipped with the theme, and new RouteLayer(map, { endpoints: true }) adds branded start, destination and numbered waypoint markers to a drawn route. IsochroneLayer renders reachability rings from the gateway's POST /isochrone in one call, and map.map (the raw MapLibre map) takes any layer the MapLibre style spec can draw: the add your own data guide covers all of it, with worked choropleth and heatmap examples.

The SDK runs from any origin: the gateway answers with Access-Control-Allow-Origin: *, so browser calls work from ordinary web apps and from null-origin contexts alike: Figma plugins, Electron apps, file:// pages. Keys travel as bearer headers, never cookies, which is what makes the open policy safe.

Errors

route() throws a plain Error. Gateway errors (401 bad key, 429 rate limit; RFC 9457 problem+json on the wire) surface as route request failed: HTTP <status> (<title> - <detail>); routing-engine failures (OSRM-shaped bodies with a code) surface as OSRM routing failed: <code> - <message>. The full error envelope, including 402-vs-429, is in conventions.

ts
try {
  await routes.route(from, to, { profile: "truck" });
} catch (err) {
  // e.g. "route request failed: HTTP 401 (...)"; check your snk_ key
  // e.g. "OSRM routing failed: NoRoute - ...";   no legal route exists
  console.error(err);
}

Turn-by-turn guidance

Request voice and banner instructions on the route, then use the guidance helpers:

ts
import { extractGuidance, speak, GuidanceBanner } from "@mapmap/maps";

const route = await routes.route(from, to, {
  profile: "truck",
  voice: true,    // spoken voiceInstructions on each step
  banner: true,   // visual bannerInstructions, with lane data
  language: "en-GB",
});

const steps = extractGuidance(route);          // one StepGuidance per step
const banner = new GuidanceBanner(document.body, map.navDesign?.banner);
banner.update(steps[0]?.banners[0] ?? null);   // render the next maneuver
if (steps[0]?.voice[0]) speak(steps[0].voice[0], { lang: "en-GB" });

Each step's voice array is ordered by descending trigger distance; speak each instruction once as its distance is crossed; de-duplication is the caller's responsibility.

NavigationCamera is the turnkey chase cam: tilted (pitch 60, clamped 0–85), course-up, zoom 17, with the puck anchored low-centre (anchorY 0.72) so the camera looks up the road. Feed it from the same loop that drives your guidance:

ts
import { NavigationCamera, PositionPuck } from "@mapmap/maps";

const camera = new NavigationCamera(map, { pitch: 60, zoom: 17 });
camera.attachPuck(new PositionPuck(map)); // one call now moves both
navigator.geolocation.watchPosition(({ coords }) =>
  camera.follow({ lat: coords.latitude, lon: coords.longitude }, coords.heading ?? undefined),
);

Every follow(fix, courseDeg?) glides with an interruptible linear ease (duration easeMs, default 900 ms, capped by the observed fix interval), sets the bearing to the course (or holds it when courseDeg is omitted), and co-drives an attached puck. Any user drag / rotate / pitch / zoom switches the camera to "free" mode and it recentres itself after autoRecentreMs idle (default 6 s; 0 disables; call resume()). overview(route.geometry) fits the whole route top-down and resume() returns to the chase cam; camera.mode reports "follow" | "overview" | "free", and destroy() removes the listeners. NavigationCamera.isSupported(map) returns false under the globe projection, whose camera geometry breaks the low-anchor offset maths; switch the map to mercator before navigating.

The PositionPuck interpolates between fixes by default: it glides along the shortest arc from its rendered position to each new fix over a duration matched to the observed fix interval, so the puck and camera arrive together instead of the puck teleporting once a second. Pass { interpolate: false } to snap instead.

To draw the vehicle as one of MapMap's own 3D-rendered cars instead of the dot and arrow, use AvatarPuck from @mapmap/maps/avatars: the same setLocation and remove, in its own entry point so apps that never draw a vehicle never load it. See Vehicle avatars.

Progress line & manoeuvre arrows

Dim the travelled part of the route (the "vanishing route line") and drop a rotated arrow at the next turn; both survive a light/dark style swap:

ts
routes.setProgress(0.42);              // 0–1 of the route length, travelled
routes.setManeuver([lon, lat], 135);   // arrow at the next turn, bearing°
// …later
routes.setProgress(0);                 // restore the plain line
routes.clearManeuver();

setProgress renders a line-gradient over the route source (built with lineMetrics); pass a progressColor in the layer options to change the dimmed colour. Derive the fraction from the guidance module's distance-remaining.

Day/night & label language

Switch light/dark automatically by sun position, and labels by language; both dependency-free and offline-capable (territory packages ship paired light/dark styles and the OpenMapTiles multilingual name:* fields):

ts
import { ThemeScheduler, setMapLanguage } from "@mapmap/maps";

// Flip between light and dark at local sunrise and sunset, re-armed each boundary.
const scheduler = new ThemeScheduler({
  lat: 51.5, lng: -0.13,
  onLight: () => map.setStyle("light"),
  onDark:  () => map.setStyle("dark"),
});
// scheduler.dispose() to stop.

setMapLanguage(map, "de");   // relabel in German; null restores the default

ThemeScheduler handles polar day/night; resolveTheme(date, lat, lng) is the one-shot form. setMapLanguage rewrites only name-label layers (road shields and house numbers are left alone) and validates the tag. For right-to-left scripts, also install MapLibre's RTL text plugin in your app.

Using your Studio design

A theme designed in Studio carries its navigation look: route line, position puck, banner and safety alerts, under extra.nav in the theme JSON you download or copy. Pass that theme file to createMap and the navigation UI styles itself:

ts
import { createMap, RouteLayer, GuidanceBanner, PositionPuck } from "@mapmap/maps";
import theme from "./midnight-fleet.theme.json"; // downloaded from Studio

const map = createMap({ container: "map", apiKey: "snk_...", style: theme });
await map.whenReady();

const routes = new RouteLayer(map);   // line colour/width/opacity + casing
const banner = new GuidanceBanner(document.body, map.navDesign?.banner);
const puck = new PositionPuck(map);   // dot + heading arrow, or custom image
puck.setLocation({ lat: 51.5074, lon: -0.1278 }, 45); // heading in degrees

The alerts block (optional since v1) styles safety-camera alerts: CameraAlertChip renders the chip in its calm and escalated states with per-kind icons, and RouteLayer.setAlertCorridors tints average-speed corridors on the route line.

ts
import { CameraAlertChip } from "@mapmap/maps";

const chip = new CameraAlertChip(document.body, map.navDesign?.alerts);
chip.update({ kind: "fixed", limitKph: 30, distanceM: 240 }, { speeding: false });

The visual alert is unconditional and calm; audio is the escalation channel, so a driver within the limit still sees the chip and hears it only when the kind's alertMode says so. Chip positions are a fixed set of slots rather than free coordinates, so an alert can never cover the speed or the limit. On CarPlay and Android Auto, alerts render from the platform's own template, so read alertChipContent for the title, subtitle and icon and let the colours degrade gracefully.

Whether cameras may be shown at all is a server-side jurisdiction policy applied per country before the response leaves the gateway. The design styles what policy permits and cannot widen it.

A theme document passed to createMap compiles in the browser with the SDK's own buildStyle, which in 0.25.1 knows all 32 of the hosted compiler's palette slots, the six footpath slots and pedestrianArea included, and draws the six road-path-* layers. See palette slots.

map.navDesign is the parsed block (navDesignFromTheme / parseNavDesign are exported too); RouteLayer and PositionPuck pick it up automatically, and without a nav block everything keeps the SDK's built-in look.

The block also survives hosted publishing: it travels with the theme document, stored on publish, served back from GET /styles/{id}/theme (public, uncached), while the compiled style.json never carries it. Fetch it from a hosted style with navDesignFromThemeUrl:

ts
import { navDesignFromThemeUrl } from "@mapmap/maps";

const design = await navDesignFromThemeUrl(
  "https://api.mapmap.ai/styles/midnight-fleet-a1b2c3/theme",
);
const banner = new GuidanceBanner(document.body, design?.banner);

The map renders the attribution required by our data licence and the MapMap mark, and neither can be removed by configuration. As of 0.8.0, mapOptions: { attributionControl: false } and logo: false are accepted, ignored and reported with one console.warn per map rather than honoured, and as of 0.14.0 so is attributionControl: { compact: true }: the credit is always shown in full. What still works: { customAttribution } adds your own credit alongside the OpenStreetMap one, attributionPosition picks the credit's corner, and logo: { position, href } moves or relinks the mark.

Your own data: slots, persistent layers and DataLayer

From 0.17.0. The names follow Mapbox GL JS, so code written for Mapbox Standard reads the same.

ts
import { DataLayer, SLOT_ANCHORS, SLOTS, resolveSlot } from "@mapmap/maps";

// Slots: "bottom" (above land and water, below roads and buildings),
// "middle" (above roads, below labels), "top" (above POI labels, below
// place labels). map.slot() returns the beforeId on the live style.
map.map.addLayer(myLayer, map.slot("bottom"));

// Persistent sources and layers come back after every setStyle, in order.
map.addPersistentSource("depots", { type: "geojson", data: depots });
map.addPersistentLayer({ id: "depots", type: "circle", source: "depots" }, { slot: "middle" });
map.setStyle("dark");

// DataLayer: inline or URL GeoJSON, or your own PMTiles.
const zones = new DataLayer(map, {
  data: "pmtiles://https://r2.example.com/zones.pmtiles",
  sourceLayer: "zones",
  style: { graduated: { property: "orders", stops: [[0, "#d9a13a"], [500, "#e05c6c"]] } },
  slot: "bottom",
});
zones.on("select", (e) => console.log(e.selected));

// Interactions over the basemap featuresets: poi, place-labels, buildings.
map.addInteraction("poi-click", {
  type: "click",
  target: { featuresetId: "poi" },
  handler: ({ feature }) => true, // true stops propagation
});
  • SLOTS, SLOT_ANCHORS, isSlot and resolveSlot(style, slot) (type Slot) resolve a slot on any style; custom styles fall back to the first road- layer, the first symbol layer and city-labels, then append.
  • addPersistentLayer(layer, PersistentLayerOptions) takes { slot, beforeId }; persistentIds() returns PersistentIds; removePersistent drops a source with its layers.
  • DataLayer takes DataLayerOptions: mode (DataLayerMode: auto, point, line, polygon, cluster, heatmap, extrusion), style (DataLayerStyle with DataLayerSimpleStyle, DataLayerCategories or DataLayerGraduated), cluster (DataLayerClusterOptions), extrusion (DataLayerExtrusionOptions), promoteId, hover, select, popup, slot, attribution, fitBounds. Handlers get a DataLayerEvent. dataLayerColor(style) returns the colour expression a style compiles to, and applyGeoJSONDiff(data, diff) applies a MapLibre GeoJSON diff to a FeatureCollection, as updateData does locally.
  • addInteraction(id, Interaction) with InteractionType (click, mouseenter, mouseleave, mousemove), an InteractionTarget (layerId or featuresetId, type FeaturesetId) and a handler receiving an InteractionEvent. FEATURESETS and featuresetLayerIds list the basemap layers behind each featureset; liveTargetLayerIds the ones on the live style. InteractionRegistry does the same for a plain maplibregl.Map.
  • POI and place labels carry stable ids, so hover and selection on them are exact. Buildings are best effort: the tiles merge neighbouring footprints of the same height into one feature.

Colour themes

Grade the whole map through a colour theme, a 16x16x16 lookup table, the way Mapbox setColorTheme does. A Mapbox colour-theme PNG (256x16) works as it is.

ts
await map.setColorTheme({ data: "https://example.com/night.png" }); // PNG: URL, data URI or raw base64
await map.setColorTheme({ lut: bytes, strength: 0.6 });             // or the 12288 LUT bytes
map.getColorTheme();                                                 // { digest, strength }
map.setColorTheme(null);
  • Everything on screen is graded, labels, terrain and your own layers included; the theme stays on top of layers added later and survives setStyle.
  • strength runs from 0 to 1 (default 1); at 0 the theme draws nothing and costs nothing.
  • It costs one full-frame copy per frame, worth knowing on high-density phone screens.
  • ColorThemeSpec is the argument type. The theme is drawn by ColourThemeLayer (ColourThemeLayerOptions) under the id COLOUR_THEME_LAYER_ID, and lutFromPngData decodes a PNG to LUT bytes.
  • Pure helpers for tools and build steps: lutApply, gradeColourString, gradeStyleColours (GradeStyleOptions), lutDigest, lutFromBase64, lutToBase64, lutFromImageData, lutToImageData (LutImageData), buildLut, IDENTITY_LUT, LUT_SIZE and LUT_BYTES; a LutBytes is the 12288 bytes of a 16x16x16 RGB table, red fastest.
  • Or bake it into the style. A theme's color_theme block (a ColourTheme) grades every colour at compile time, so the hosted style, static maps and the mobile apps show the same grade with no runtime layer; "use_theme": "none" (a UseTheme) keeps one layer as written. See the theme document for the block. buildStyle does it through applyColourTheme, validateColourTheme, validateUseTheme and colourThemeMetadata, and the style carries metadata[COLOUR_THEME_METADATA_KEY] with the LUT digest. Ready-made strips: night for a light map, night-dark for a dark one, mono, warm and cool.

3D models and 3D Tiles

glTF models from the @mapmap/maps/models subpath and OGC 3D Tiles from @mapmap/maps/tiles, correct on mercator and on the globe. Each subpath needs only its own optional peers, and apps that import neither load neither:

sh
npm install three                     # models
npm install three 3d-tiles-renderer   # 3D Tiles as well
ts
import { ModelLayer } from "@mapmap/maps/models";
import { TilesLayer } from "@mapmap/maps/tiles";

const models = new ModelLayer(map);
await models.add({ id: "tower", url: "/models/tower.glb", lngLat: [-0.1246, 51.5007], bearingDeg: 12, clip: true });
const tiles = new TilesLayer(map, { url: "https://example.com/tileset/tileset.json" });
ModelSpecMeaning
id, urlA unique id and a .glb (meshopt-compressed or plain).
lngLat, altitudeMWhere the model's base stands, and metres above the ground (default 0).
bearingDeg, scaleCompass bearing clockwise from north, and a uniform scale (model units are metres).
cliptrue hides the basemap's buildings under the model's footprint; a Polygon is used as given.
  • The layer survives setStyle, sits directly above the 3D buildings by default (slot or beforeId to move it) and shares their depth, so buildings and models hide each other correctly.
  • Globe: each model is drawn at its own anchor through the same helper as the SDK's other custom layers (see "Custom layers and the globe" in the maps reference), within a pixel on mercator, on the globe and through the zoom band where the globe turns flat.
  • Terrain: terrain: "clamp" (default) stands a model on the terrain under its anchor; a long model does not follow the ground until MapLibre 6.13's draping hooks are supported.
  • TilesLayer (from @mapmap/maps/tiles since 0.19.0; it was in @mapmap/maps/models in 0.18) takes url, anchor (default: the tileset's own centre), errorTarget, maxDepth and clip; tiles.tiles is the 3DTilesRendererJS renderer for plugins and events.
  • Helpers for apps with their own three.js scene: loadGlb, placeModel, localOffset, lngLatFromLocal, bearingToRotationY and footprintPolygon.
  • One copy of three per app (npm ls three).

Clipping the basemap under your data

map.addClip hides the basemap's buildings (and, on request, POI labels) inside a polygon, the way a Mapbox clip layer does. It works on its own, with no model:

ts
map.addClip("new-tower", { polygon: site });                                // buildings
map.addClip("plaza", { polygon: plaza, types: ["buildings", "symbols"] }); // and POI labels
map.removeClip("new-tower");
map.clips();
  • A feature touching the polygon is not drawn; each layer's own filter comes back when its last clip is removed. Clips survive setStyle.
  • ClipOptions: polygon (a Polygon or MultiPolygon of at most CLIP_MAX_VERTICES, 500, vertices), types (a ClipType, "buildings" by default, or "symbols"; the layer ids are in CLIP_TARGETS), layers (your own layer ids instead) and minzoom (CLIP_DEFAULT_MINZOOM, 13: the test is evaluated per feature per tile, so it stays off low zooms).
  • clipFilter(polygon, filter, minzoom) returns the filter itself, for styles you assemble by hand; it works on MapLibre Native too.

The package has over 200 named exports, types included: map, routing, ADR, guidance, markers, places, styling and coordinate helpers. This page shows the main ones; a generated TypeDoc reference ships with the npm release.

Point clouds: @mapmap/points

Availability: live on npm, 0.6.0.

LiDAR and photogrammetry point clouds drawn inside the map's own WebGL context, from a baked payload or a COPC file streamed over HTTP range requests, plus the client types for measured clearance on a route.

bash
npm install @mapmap/points three maplibre-gl

Everything else, from the minimal example, supported formats and device budgets to the full API reference, is on its own page: Point clouds. The clearance types are under clearance on route.

Tiling: @mapmap/tile

Availability: live on npm, 0.1.0 (13 October 2026). Free to use under the Apache License 2.0: no account, key or agreement.

Tile a GeoJSON file into a PMTiles archive of vector tiles, on your own machine or in the browser. Nothing is uploaded: the archive is a file you host on your own bucket or serve from your own gateway. It is the MapMap tiler (the native mapmap-tile binary, run as snfactory tile in the self-host distro) compiled to WebAssembly, and the same input and flags give a byte-identical archive whichever one you run.

bash
npm install @mapmap/tile

The command line and the Node entry need Node 18 or later; in the browser it needs WebAssembly. The package has no peer and no runtime dependencies.

Inputs. A FeatureCollection, a single Feature or a bare geometry as GeoJSON, or GeoJSON Lines with one feature per line. Point, LineString, Polygon and each Multi form, in WGS84 longitude and latitude. A bad input is refused with the line or feature index and the reason, and leaves no archive behind.

Command line

bash
npx @mapmap/tile depots.geojson -o depots.pmtiles \
  --layer depots --maxzoom 14 \
  --attribution "(c) Example Council 2026"

For a file of three depots in London it prints:

text
wrote depots.pmtiles (0.0 MB): 3 features into 26 tiles, layer "depots", z0-z14
  bounds: -0.14000, 51.48000, -0.09000, 51.53000
  tiles per zoom: z0:1 z1:2 z2:2 z3:2 z4:2 z5:2 z6:1 z7:1 z8:1 z9:1 z10:1 z11:2 z12:2 z13:3 z14:3
  next: copy it into the gateway's SN_TILES_DIR, then
        GET /tiles/depots/{z}/{x}/{y}.mvt, /tiles/depots/tiles.json and /tiles/depots/style.json
        source-layer in your style: "depots"

Installed, the same command is mapmap-tile.

FlagDefaultNotes
<INPUT>requiredOne file. .geojsonl, .geojsons, .ndjson and .jsonl are read as GeoJSON Lines, anything else as GeoJSON
-o, --outrequiredThe archive to write. Name it <id>.pmtiles in lowercase letters, digits and hyphens to serve it from a MapMap gateway as it is. Refuses to overwrite without --force
--layerdataThe MVT layer name, which is the source-layer your style references
--minzoom / --maxzoom0 / 14Whole numbers; --maxzoom is at most 22. Renderers overzoom past it, so deeper is rarely worth the tiles
--namethe layer nameTitle in the archive metadata
--attributionnoneCredit recorded in the archive. A warning is printed when it is absent
--forceoffReplace an existing archive
--max-input-mb256Refuse inputs larger than this many megabytes
-h, --help / -V, --versionPrint the usage or the version

The archive is written under a temporary name and renamed, so a failed write never leaves half an archive where a good one was. The exit code is 0 on success, 2 for a usage error, and 1 for any other failure: an existing archive without --force, an unreadable input, a tiling error or a failed write.

In code

ts
import { tileWithReport } from "@mapmap/tile";

const depots = {
  type: "FeatureCollection",
  features: [
    { type: "Feature", properties: { name: "North" }, geometry: { type: "Point", coordinates: [-0.14, 51.53] } },
    { type: "Feature", properties: { name: "Centre" }, geometry: { type: "Point", coordinates: [-0.12, 51.5] } },
    { type: "Feature", properties: { name: "South" }, geometry: { type: "Point", coordinates: [-0.09, 51.48] } },
  ],
};

const { archive, report } = await tileWithReport(JSON.stringify(depots), {
  layer: "depots",
  attribution: "(c) Example Council 2026",
});
console.log(`${report.features} features into ${report.tiles} tiles, ${archive.byteLength} bytes`);
// => 3 features into 26 tiles, 19139 bytes

In Node, save it with writeFile("depots.pmtiles", archive) from node:fs/promises, or pass await readFile("depots.geojson") as the input. The same import works in Node, as an ES module or through require, and in the browser, where the WebAssembly (about 276 KB) is fetched from next to the module when it is needed. Bundlers that understand new URL(..., import.meta.url) copy it for you; init(url) loads it from anywhere else. In the browser, tiling a file the visitor picks:

ts
import { tile } from "@mapmap/tile";

const picker = document.createElement("input");
picker.type = "file";
picker.accept = ".geojson,.json";
document.body.append(picker);

picker.addEventListener("change", async () => {
  const file = picker.files?.[0];
  if (!file) return;
  const archive = await tile(await file.arrayBuffer(), {
    layer: "depots",
    attribution: "(c) Example Council 2026",
    onProgress: ({ zoom, maxzoom, tiles }) => console.log(`z${zoom} of z${maxzoom}: ${tiles} tiles so far`),
  });
  const link = document.createElement("a");
  link.href = URL.createObjectURL(new Blob([archive.slice()]));
  link.download = "depots.pmtiles";
  link.click();
});

The exports:

  • tile(input, options?) resolves to the archive as a Uint8Array.
  • tileWithReport(input, options?) resolves to { archive, report }. The TileReport has layer, features (read from the input), tiles (written), perZoom (tiles per zoom, keyed by zoom), bounds ([west, south, east, north] in degrees), minzoom and maxzoom (the zooms the archive holds) and bytes (the archive's size).
  • init(moduleOrPath?) loads the WebAssembly in the browser and is a no-op in Node. tile and tileWithReport call it for you; call it yourself with a URL string, a URL, a Response or a compiled WebAssembly.Module to load it from elsewhere.
  • version() returns the package version. In the browser, call it after init().

input (the TileInput type) is the file as a string, a Uint8Array, an ArrayBuffer or any other ArrayBufferView; anything else rejects with a TypeError. Every other failure rejects with an Error whose message is the one the command line prints, flag names included, for example this build would exceed 500000 tiles at zoom 14: lower --maxzoom (every extra level is four times the tiles).

TileOptions, all optional:

OptionDefaultNotes
layer"data"The MVT layer name, 1 to 255 characters
minzoom0Shallowest zoom to build
maxzoom14Deepest zoom to build, at most 22
namethe layer nameTitle in the archive metadata
attributionnoneCredit in the archive metadata. No warning is raised in code
format"auto""geojson" or "geojsonl"; "auto" reads one document as GeoJSON and one per line as GeoJSON Lines
maxInputBytes256 MiBRefuse larger inputs
onProgressnoneCalled after each zoom with a TileProgress: zoom (just finished), tiles (written so far, across every zoom), minzoom and maxzoom (the run's range). An error thrown inside it does not stop the run

Serving the archive

  • On your own bucket. Any host that serves HTTP byte ranges with CORS. Add it to a map as a vector source at pmtiles://https://your-bucket.example.com/depots.pmtiles; see bring your own tiles.
  • On your own MapMap gateway. Copy it into SN_TILES_DIR as <id>.pmtiles. It is served at /tiles/<id>/{z}/{x}/{y}.mvt with no registration step, /tiles/<id>/tiles.json carries your attribution, and /tiles/<id>/style.json is a minimal style that draws it; see tile your own data.

Limits

  • The whole input is read into memory before tiling. The input, the parsed features and the archive share one 32-bit WebAssembly memory, so inputs over 256 MB are refused by default (--max-input-mb, maxInputBytes). For bigger files, use the native tiler (snfactory tile in the self-host distro).
  • A build is capped at 500,000 tiles, and the error names --maxzoom as the setting to lower: each extra zoom level is four times the tiles.
  • One layer per archive.
  • The sole simplification is rounding to the tile grid (4096 extent, 64 buffer), so a dense line at low zoom keeps more vertices than a Douglas-Peucker pass would leave.
  • Attributes: strings, numbers and booleans carry across as themselves, nested objects and arrays as compact JSON strings, and null is dropped (a vector tile has no null).
  • GeometryCollection is refused rather than split, so the feature count you get back is the one you sent.
  • A zoom where every feature is too small to draw holds no tiles, so the archive starts at the shallowest zoom that has some; the report's minzoom and the command line's summary say so.

Licence

@mapmap/tile is Apache-2.0, copyright MapMap AI Ltd (LICENSE in the package). The open-source Rust crates compiled into its WebAssembly keep their own permissive licences, listed with their texts in THIRD-PARTY-NOTICES.md. Your data keeps its licence: if it is derived from OpenStreetMap, ODbL requires the "© OpenStreetMap contributors" credit, so pass it as --attribution (or attribution) and it travels inside the archive.

Core (WASM): @mapmap/core

Availability: live on npm, 0.4.0.

Two builds in one package. Node resolves the wasm-pack nodejs build (CommonJS, no init() needed); browsers, bundlers and workers resolve the web build (web/sn_nav_web.js), which needs await init() before any other call. @mapmap/core/node and @mapmap/core/web pin one explicitly.

The navigation core compiled to WebAssembly, for offline or worker-side use without a map: ADR tunnel compliance, offline route-request building, route parsing, polyline codecs, and the same Ferrostar-derived guidance state machine the mobile SDKs run. The example below is the Node build.

bash
npm install @mapmap/core
js
const { checkTunnel, buildOfflineRouteRequest } = require("@mapmap/core");

// May this load use a category D tunnel? (ADR 8.6.4, worst-case reading)
checkTunnel({ hazmat: true, tunnelCode: "C" }, "D");
// => { status: "blocked", reason: "..." }  or  { status: "allowed" }

// Build a turn-by-turn request any Valhalla endpoint accepts;
// hosted API, self-hosted server, or an on-device engine:
const body = buildOfflineRouteRequest(
  [{ lat: 51.1279, lon: 1.3134 }, { lat: 52.4862, lon: -1.8904 }],
  "truck",
  { heightM: 4.0, grossWeightT: 40, hazmat: true, tunnelCode: "D" },
);

The full surface: version(), checkTunnel(profile, category), forbiddenCategories(profile), buildOfflineRouteRequest(locations, costing, adrProfile), parseRouteSummary(json) (returns { distanceM, durationS, hasToll, hasHighway, hasFerry }), polylineDecode / polylineEncode (precision 5 or 6), and GuidanceSession: construct it from a route response JSON, stream location fixes in with updateLocation(lat, lon, timestampMs, …), and each call returns the updated { state: "navigating" | "arrived" | "offRoute", … }. GuidanceSession also has advanceToNextStep(), a totalSteps getter, and enableProbe(config) / finishProbeJson(arrived, timestampMs) for the per-trip probe contribution.

React Native: @mapmap/react-native

Availability: live on npm, 0.5.0.

An Expo module over the same native SDKs: signed territory install and lifecycle, on-device routing with typed geometry and manoeuvres, a typed guidance event stream, and voice guidance.

sh
npx expo install @mapmap/react-native

Register the config plugin in app.json or app.config.js. It writes the NSLocation*UsageDescription keys the SDK's location provider needs (the SDK declares none of its own) and enables the location and audio background modes, so guidance and voice keep running with the screen off:

jsonc
{
  "expo": {
    "plugins": [
      ["@mapmap/react-native", {
        "locationWhenInUsePermission": "Shown when asking for foreground location.",
        "locationAlwaysPermission": "Shown when asking for background location."
      }],
      ["expo-build-properties", { "android": { "minSdkVersion": 26 } }]
    ]
  }
}

Then build a dev client with npx expo run:ios or npx expo run:android.

minSdk 26 again. The same floor as the Android SDK, and above Expo's default, so the expo-build-properties line above is not optional.

Not available in Expo Go. The native module needs a dev client. Pass true to getMapmapNav for a pure TypeScript simulator with an identical surface, which is what Expo Go, unit tests and Storybook-style UI work should use. Importing the package never requires the native module: the native handle resolves lazily, on first use.

ts
import { getMapmapNav, addGuidanceListener } from "@mapmap/react-native";

const nav = getMapmapNav(false); // true → the mock
await nav.init("snk_…");

await nav.installTerritory("uk"); // signed, verify-then-promote
// nav.cancelTerritoryInstall("uk") stops an install in flight: a "cancelled"
// territoryProgress event, an E_CANCELLED rejection, nothing partial on disk.
const { routes } = await nav.computeRoute({
  profile: "car",
  origin: { latitude: 51.5074, longitude: -0.1278 },
  destination: { latitude: 51.5081, longitude: -0.0759 },
});

Two conditions on that happy path, one per platform. Both fail closed with a named error code rather than degrading, so read them before you build.

Android: the factory verifying key, and first install

android/build.gradle needs the territory channel's ed25519 verifying key baked in at build time, via the mapmap.factoryPubkeyHex Gradle property or the MAPMAP_FACTORY_PUBKEY_HEX environment variable. Without it init() rejects with E_INIT_FAILED, deliberately, rather than failing later inside the core.

properties
# android/gradle.properties, or -Pmapmap.factoryPubkeyHex=… on the build
mapmap.factoryPubkeyHex=<the channel's ed25519 verifying key, hex>

For the hosted channel, use its published factory key (see the hosted channel's verifying key; TerritoryKeys.HOSTED_FACTORY_KEY_HEX in the Android SDK). A self-hosted channel uses its own. It is the anchor the verify-then-promote install checks every package against, so it is not a value to copy between channels.

On ai.mapmap:core 0.3.0, installTerritory(id) for a territory that is not yet installed rejects with E_INTERNAL. The core installs a first territory only from a local .snpkg or package directory (installSnpkg / installDir), and the hosted channel serves an index, manifests and layer blobs but no package archive yet. Updating an already-installed territory works end to end, signed differential update included. Ship the first .snpkg with the app or side-load it until the channel serves archives.

iOS: on-device routing needs MapMapValhalla

computeRoute runs Valhalla on the device through the iOS SDK's MapMapValhalla product, which ships only via SwiftPM; there is no binary pod for it yet. Add the package to your app target (File, Add Package Dependencies…, https://github.com/Mapmapai/mapmap-ios) and link MapMapValhalla. Without it the bridge still builds and everything else works, but computeRoute rejects with E_INTERNAL rather than pretending. The CocoaPods dependency MapMapKit (~> 0.9.0) covers the rest of the SDK; until it is on the CDN, pin it in your Podfile:

ruby
pod 'MapMapKit', podspec: 'https://raw.githubusercontent.com/Mapmapai/mapmap-ios/main/MapMapKit.podspec'

On bare React Native, install expo-modules-core alongside it (that peer is required; the expo package itself is optional and never imported at runtime), follow Expo's bare install guide, set minSdkVersion 26, and apply the Info.plist keys and background modes by hand, since the config plugin only runs under Expo prebuild.

API reference

The full JS surface of @mapmap/react-native.

Getting a handle.

  • getMapmapNav(useMock, mockOptions?) returns a MapmapNavHandle: the real native module when useMock is false, the pure-TypeScript mock when true. MapmapNavHandle is MapmapNavModule (the promise-based method surface) intersected with the typed event emitter.
  • createMapmapNavMock(options?) builds a MapmapNavMock directly, for tests and UI work that want the simulator without going through getMapmapNav. MapmapNavMock implements the whole MapmapNavModule contract in TypeScript with zero native dependency: phased installTerritory progress, a plausible multi-route computeRoute, a guidance loop that emits at roughly 1 Hz, and a voice pulse on each banner change.
  • MapmapNavMockOptions tunes the simulator: tickIntervalMs (guidance tick, default 1000), territoryInstallDurationMs (default 3000), simulateReroute (default true), and routeProvider, an optional callback that returns real routes so demo guidance follows real roads and only falls back to the synthetic dogleg when it returns null.
  • NativeMapmapNavModule is the type of the real native-backed handle (MapmapNavModule plus the emitter surface). The native module is resolved lazily on first use, so importing the package never requires it.

Events. Each helper attaches a typed listener and returns an EventSubscription (from expo-modules-core; call .remove() to detach). They work identically against the real handle and the mock, because both satisfy MapmapNavEmitterLike.

  • addGuidanceListener(handle, listener) for the guidance stream.
  • addTerritoryProgressListener(handle, listener) for TerritoryProgressEvents during a download.
  • addVoiceStateListener(handle, listener) for VoiceStateEvents ({ muted, volume, speaking }).
  • addBridgeErrorListener(handle, listener) for a BridgeError raised outside a rejected promise (for example inside the guidance loop).
  • MapmapNavEmitterLike<Events> is the structural emitter shape both handles implement (addListener, optional removeAllListeners), and MapmapNavEvents is the event-name to payload map (territoryProgress, guidance, voiceState, bridgeError).

Custom regions. Download an area you choose (a bounding box, a GeoJSON polygon or an administrative boundary) instead of a whole country. The gateway cuts it out of a signed country package on its job lane (POST /v1/jobs/territory) and publishes it as a territory of its own, with a region- id.

  • createCustomRegionClient({ apiKey, gatewayBaseUrl?, fetch? }) returns a CustomRegionClient: requestCustomRegion(request), getCustomRegionJob(jobId), waitForCustomRegion(jobId, options?), requestAndWait(request, options?), searchBoundaries(search) and getBoundary(boundaryId).
  • A CustomRegionRequest carries exactly one of bbox ([west, south, east, north]), polygon or boundaryId, plus optional layers (any of valhalla-tiles, pmtiles, geocode-index, style; all four by default), source and webhookUrl.
  • installCustomRegion(nav, region) installs (or, after a re-cut, updates) the result through the native core, with the same territoryProgress events and cancelTerritoryInstall as installTerritory. The client's calls reject with a CustomRegionError carrying a CustomRegionErrorCode (for example E_REGION_REFUSED for a 422, E_REGION_FAILED for a failed job); installCustomRegion rejects with a BridgeError like any other install.
  • The native builds pin the hosted gateway's region key, HOSTED_REGION_KEY_HEX, which the core accepts for region- ids and never for a country package. For a self-hosted gateway set mapmap.regionPubkeyHex / MAPMAP_REGION_PUBKEY_HEX on Android and the Info.plist key MAPMAP_REGION_VERIFYING_KEY on iOS.

Errors and payloads.

  • BridgeError is { code: BridgeErrorCode, message }, carried on every rejected promise. BridgeErrorCode is the stable machine-readable set: E_NOT_INITIALISED, E_INIT_FAILED, E_NETWORK, E_AUTH, E_TERRITORY_ALLOWANCE, E_TERRITORY_VERIFY, E_TERRITORY_NOT_FOUND, E_NO_TERRITORY, E_NO_ROUTE, E_GUIDANCE_ACTIVE, E_NO_GUIDANCE, E_REPLAY_CORPUS, E_CANCELLED (an install stopped by cancelTerritoryInstall) and E_INTERNAL.
  • TerritoryPhase is "downloading" | "verifying" | "activating" | "done" | "failed" | "cancelled", and TerritoryProgressEvent carries { territoryId, phase, bytesDone, bytesTotal, error? }.
  • VoiceStateEvent is { muted, volume, speaking }.
  • LocationSource (part of GuidanceOptions) is either { kind: "live" } or { kind: "replay", corpusPath, speedMultiplier? }, so guidance can be driven from live GPS or from a recorded .drive.jsonl corpus for desk demos.

Offline coverage drives

Availability: from ai.mapmap:core 0.9.0, MapMapKit 0.9.0 and @mapmap/react-native 0.5.0.

Plan online, drive offline. A coverage plan (drive every street of an area, POST /v1/jobs/coverage) is made on the hosted API and metered there as always. With the territory that covers the area installed, the two things a driver needs with no signal run on the phone:

  • Guidance for a drive: one outing, the transfer into it, or the drive back to the start, the answer POST /v1/coverage/guidance gives (one leg per piece of the drive's trace_route_parts, with manoeuvres, distance, time and polyline6 shape). Every piece is walked with the on-device engine's exact edge walk, never map matched.
  • Re-planning round a closed street: the rest of a drive from where the car is, round what is closed, the answer POST /v1/coverage/reroute gives (a chunk ready for guidance, with skipped and detour_km), computed on the territory's own routing tiles by the same code the hosted endpoint runs.

Requests and answers are the hosted ones, so the same code reads either: name the drive with chunk_id and drive (the stored job stands in for job_id), or send it inline (chunk for guidance, trace_route for a re-plan).

What needs a connection, and what does not.

StepConnection
Install or update the territoryNeeded (a download, metered against the key's allowance)
Make the plan, POST /v1/jobs/coverage, and fetch the finished jobNeeded (billed as a coverage plan)
Guide a drive of the planNot needed
Re-plan a drive round a closed streetNot needed
Plan a new areaNeeded: plans are made on the hosted API only

Keep the finished job as GET /v1/jobs/{id} answers it, and the body you submitted (its include_private and turn_penalties are what a re-plan defaults to, as for a hosted job_id request).

React Native:

ts
import {
  OfflineCoverageError,
  coverageGuidanceOffline,
  coverageRerouteOffline,
  getMapmapNav,
} from "@mapmap/react-native";

const nav = getMapmapNav(false);
// job: the finished coverage job you fetched while online; submitted: its request body.
const guidance = await coverageGuidanceOffline(nav, {
  plan: job,
  request: { chunk_id: 3, drive: "outing" },
});
// guidance.trip.legs: one leg per piece, as the hosted answer.

try {
  const replan = await coverageRerouteOffline(nav, {
    plan: job,
    planRequest: submitted,
    request: {
      chunk_id: 3,
      position: { lat: 50.8226, lon: -0.1372, heading: 90 },
      step_index: 41,
      avoid: { way_ids: [26574320] },
    },
  });
  const next = await coverageGuidanceOffline(nav, { request: { chunk: replan.chunk } });
} catch (e) {
  if (e instanceof OfflineCoverageError && e.kind === "map_version_mismatch") {
    // The territory is another map than the plan's: update it, or plan again.
  }
}

iOS (TerritoryStore, with ValhallaMobileRouter from MapMapValhalla on the territory's .valhallaTiles layer):

swift
let tiles = try await store.layerPath(territoryId: "uk", kind: .valhallaTiles)
let router = try ValhallaMobileRouter.fromTileDir(tiles, scratchDir: cachesDir)
let guidance = try await store.coverageGuidanceOffline(
    territoryId: "uk", router: router, planJson: jobJson,
    requestJson: #"{"chunk_id": 3}"#)
let replan = try await store.coverageRerouteOffline(
    territoryId: "uk", planJson: jobJson, planRequestJson: submittedJson,
    requestJson: rerouteJson)

Android (TerritoryStore, with ValhallaMobileRouter on the territory's MapLayerKind.ValhallaTiles layer):

kotlin
val tiles = store.layerPath("uk", MapLayerKind.ValhallaTiles)
val router = ValhallaMobileRouter.fromTileDir(tiles, context.cacheDir)
val guidance = store.coverageGuidanceOffline("uk", router, jobJson, """{"chunk_id": 3}""")
val replan = store.coverageRerouteOffline("uk", jobJson, submittedJson, rerouteJson)

The map the plan was made on. A plan is made on the hosted routing graph; an installed territory is its own build of the map, from its own extract, and its internal edge ids are not the hosted graph's. So the phone never trusts a plan's edge_ids: a stored outing is placed on the territory's map by its own geometry, street for street, and must drive the plan's streets step for step. A territory built from older or newer OpenStreetMap data than the plan where the drive runs answers map_version_mismatch (with the plan's graph.osm_timestamp and the territory's version and data date) rather than a drive that is not the plan's. Re-plan answers carry graph_osm_timestamp as the territory's data timestamp, and their edge ids are the territory's.

Errors. Failures of the drive itself are typed (OfflineCoverageError on React Native and iOS, OfflineCoverageException on Android), with the same fields on every platform:

KindWhenFields
territory_not_installedNo such territory on the device, or the install left its routing layer outterritory_id
plan_outside_territoryThe car or a drive lies outside the territoryterritory_id
map_version_mismatchThe drive does not follow the territory's streetsplan_osm_timestamp, territory_version, territory_data_timestamp
piece_refusedThe engine's edge walk refused a piece (the hosted 422 coverage-guidance-refused): the walk stops there, nothing is guessedpiece, pieces, lat, lon, km, engine_error_code, engine_error
reroute_refusedNo new drive could be made (the hosted 422 coverage-reroute-refused)reason: car_not_located, nothing_reachable, nothing_left, not_one_drive, step_index_needed, step_index_past_end, too_large, out_of_time
too_largeOver a coverage ceiling (the hosted coverage-too-large)
invalid_requestA request the hosted endpoint answers with a 400, same wording
engineThe on-device engine failed rather than refused
internalA fault of ours: report it with the plan's job id

Every kind carries detail, a sentence for the driver.

React Native types: coverageGuidanceOffline(nav, options: CoverageGuidanceOfflineOptions) resolves a CoverageGuidanceAnswer, and coverageRerouteOffline(nav, options: CoverageRerouteOfflineOptions) a CoverageRerouteAnswer; plan is a StoredCoveragePlan (the job, its result, or either as a JSON string). OfflineCoverageError.kind is an OfflineCoverageErrorKind and .fields an OfflineCoverageErrorFields. The native module's own coverageGuidanceOffline and coverageRerouteOffline take a CoverageOfflineCall (JSON strings) and answer a JSON envelope; call them through the helpers. A re-plan has up to 60 seconds on the phone (20 hosted). The ceilings are the hosted defaults.

Voice guidance: @mapmap/voice (beta)

Availability: beta, on npm as 0.1.0-beta.1. The API and the voice registry can still change between betas, and the rendered text is part of every clip key, so pin the exact version.

One closed, multilingual phrasebook for spoken turn-by-turn guidance. A manoeuvre from the router becomes a locale-neutral GuidanceIntent; the words come from the phrasebook of the driver's language, never from the router's own instruction strings. Every sentence is fixed wording plus at most one road or place name, always last, and distances are spelled out from closed ladders ("four hundred yards", "anderthalb Kilometern"), so every fixed clip can be recorded ahead of time and a name clip is made once and reused. The package has no runtime dependencies and uses no DOM, Node built-ins or Intl, so the same input gives the same text on Hermes, in a browser and in Node.

bash
npm install @mapmap/voice@0.1.0-beta.1
ts
import { fromValhallaRoute, render, supportedLocale } from "@mapmap/voice";

const { locale } = supportedLocale(deviceLocale); // "de-AT" -> "de-DE"; unsupported -> "en-GB"
const intents = fromValhallaRoute(route.trip.legs[0].maneuvers);

render(locale, { intent: intents[3], stage: "preview", units: "metric", distanceM: 380 });
// de-DE: "In vierhundert Metern rechts abbiegen auf Bahnhofstraße."

render("en-GB", { intent: intents[3], stage: "imperative", units: "imperial_uk", then: intents[4] });
// "Turn right onto York Street, then turn left."

render(locale, input) returns an Utterance (text, the parts it is made of, and locale), or null when there is nothing to say. The stages are preview (led by the distance; give distanceM), imperative (at the manoeuvre) and then (a stand-alone follow-up). phrase(locale, id) returns a fixed phrase such as "level_crossing", and definePhrases(locale, table) registers your own templates with closed slots. fromValhalla(maneuver, context) converts a single manoeuvre.

The locales are en-GB, en-US, fr-FR, de-DE, es-ES, it-IT and nl-NL. In 0.1.0-beta.1 only the en-GB female voice is marked live; every other voice is a candidate, to be used behind a developer flag until a native speaker has signed off its review sheet. Read voiceFor(locale).status rather than assuming a locale is ready.

Playing it. Utterances are played from recorded clips, not synthesised on the device. voiceFor(locale, gender?) picks the voice from the registry, clipKey(voice, text, { format }) is the clip's content address, and the gateway serves the clips: POST /v1/voice/clips (with locale, optional gender and providers, and the utterances) returns each clip's url and hash, GET /v1/voice/clips/{clip} serves one, and GET /v1/voice/bank lists the clips a deployment already holds, so an app can bundle the fixed phrases at build time. enumerateFixed(locale, units) is the list of every fixed part, which is the bake list for that bundle. All three endpoints take your API key. Take each clip's hash and url from the gateway's answer rather than from clipKey: when a voice's provider fails, the gateway answers with that voice's named fallback and flags it "fallback": true. voiceFor(locale, gender, { providers: ["open"] }) restricts the choice to self-hosted open-source voices; send the same providers to the gateway.

Android (Kotlin)

Availability: ai.mapmap:core 0.9.0, published to Maven Central; no account and no token needed. The 0.2.x releases remain on GitHub Packages only. Full class-by-class API on the Android API reference.

minSdk 26. The SDK requires minSdk 26 (Android 8.0). That is above the default of many app templates; Expo projects in particular default lower, so adding the SDK forces a minSdkVersion bump in your app (an app.json / expo-build-properties change on Expo).

The current release resolves from mavenCentral() with no credentials. Only the 0.2.x releases still need GitHub Packages, which requires authentication even for public packages: a GitHub account with access to the repository and a personal access token with the read:packages scope, supplied via ~/.gradle/gradle.properties (gpr.user / gpr.token) or environment variables.

Declare the repository at the root of the build, not in a module. Projects created from current Android/Gradle templates use dependencyResolutionManagement in settings.gradle(.kts); once that block exists, a repositories {} block inside a module's build.gradle(.kts) is silently ignored (unless the project opts into FAIL_ON_PROJECT_REPOS), and dependency resolution never searches your repo. This especially bites library/RN-module authors: your module cannot supply the repository; the host app's root project must declare it.

kotlin
// settings.gradle.kts: root project, inside dependencyResolutionManagement
dependencyResolutionManagement {
  repositories {
    google()
    mavenCentral() // 0.3.0 and later; nothing else to add
    // Only needed to resolve an 0.2.x release:
    // maven {
    //   url = uri("https://maven.pkg.github.com/Mapmapai/mapmap")
    //   credentials {
    //     username = providers.gradleProperty("gpr.user").orNull ?: System.getenv("GITHUB_ACTOR")
    //     password = providers.gradleProperty("gpr.token").orNull ?: System.getenv("GITHUB_TOKEN")
    //   }
    // }
  }
}
kotlin
// app/build.gradle.kts
dependencies {
  implementation("ai.mapmap:core:0.9.0")
}

The offline territory store takes the pinned verifying key at construction (see "The verifying key" below):

kotlin
import ai.mapmap.territory.TerritoryStore

// 64-hex factory verifying key, baked in at build time (e.g. BuildConfig);
// never fetched at runtime.
val store = TerritoryStore(
    rootDir = File(context.filesDir, "territories"),
    verifyingKeyHex = BuildConfig.MAPMAP_FACTORY_PUBKEY_HEX,
)

For the hosted channel you can pass TerritoryKeys.HOSTED_FACTORY_KEY_HEX (in ai.mapmap.territory) as verifyingKeyHex; add regionKeyHex = TerritoryKeys.HOSTED_REGION_KEY_HEX to accept custom regions cut by the hosted gateway.

From 0.8.0 one call installs a territory from the signed channel, or brings an installed one up to date:

kotlin
import ai.mapmap.territory.ChannelSource

// ChannelSync: Installed, Updated, UpToDate or Cancelled.
val outcome = store.sync("uk", ChannelSource.gateway(), apiKey = "snk_...")

Every install is verify-then-promote: a package that fails signature verification leaves no trace on disk.

Android Auto

The :car and :car-maplibre modules put the same guidance state on the car's own display: a NavigationManagerBridge for the Car App Library's NavigationManager, plus a CarMapViewHost that projects your MapLibre MapView onto the car surface.

Beta, source distribution. Unlike ai.mapmap:core, these two modules are not published to Maven Central or GitHub Packages yet. Build them from the source checkout (publishToMavenLocal or a composite build); public artefacts follow head-unit hardware validation. See CarPlay & Android Auto for the install steps, the entitlement/Play Console gates, a full quickstart and DHU testing.

iOS (Swift)

Availability: installs publicly via Swift Package Manager from the distribution repository Mapmapai/mapmap-ios. Current release 0.9.0; pin from: "0.9.0", never 0.2.0 (0.2.0 shipped without its generated Swift bindings and did not compile; 0.2.1 is the fix, same binary core).

The SDK is MapMapKit: a Swift package whose FFI layer is a prebuilt binary XCFramework (UniFFI bindings over the same Rust core as Android), referenced as a checksummed binaryTarget pinned per release. Add the MapMapKit product to your target; an optional MapMapValhalla product adds the on-device Valhalla routing engine (iOS 16.4+).

swift
// Package.swift
dependencies: [
  .package(url: "https://github.com/Mapmapai/mapmap-ios", from: "0.9.0"),
],
// In your target's dependencies:
.product(name: "MapMapKit", package: "mapmap-ios"),
.product(name: "MapMapValhalla", package: "mapmap-ios"), // opt-in on-device routing
swift
import MapMapKit

let territoryDir = FileManager.default
    .urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
    .appendingPathComponent("territories")

// 64-hex factory verifying key, pinned at build time.
let store = TerritoryStore(rootDir: territoryDir, verifyingKeyHex: mapMapFactoryPubkeyHex)

// From 0.8.0: install "uk" from the signed channel, or update it.
// ChannelSync: .installed, .updated, .upToDate or .cancelled.
let outcome = try await store.sync(territoryId: "uk", source: .gateway(), apiKey: "snk_...")

For the hosted channel, TerritoryKeys.hostedFactoryKeyHex is the factory key; pass regionKeyHex: TerritoryKeys.hostedRegionKeyHex to the initialiser to accept custom regions cut by the hosted gateway.

Requires iOS 16.4 and Swift tools 5.9.

CarPlay

The optional MapMapCarPlay product orchestrates the CarPlay side end to end: the CPMapTemplate root, browse → preview → navigate activity states and the CPNavigationSession lifecycle, driven from the same NavigationEngine output.

Beta. MapMapCarPlay is a product of the public Mapmapai/mapmap-ios package from 0.7.0: add .product(name: "MapMapCarPlay", package: "mapmap-ios") to your target. See CarPlay & Android Auto for the install steps, the required Apple entitlement, a full quickstart and CarPlay Simulator testing.

The verifying key: trust anchor for offline packages

Territory packages (the offline maps the mobile SDKs consume; see territories) are ed25519-signed by the factory signing key, and each app pins the factory's 64-hex verifying key (the public half of that pair) so a tampered or substituted package is rejected on device. The pinning call is the TerritoryStore constructor shown in the Android and iOS sections above: bake the key in at build time (a build config field or bundled resource); never fetch it over the same channel as the packages it validates.

Where the key comes from: the hosted channel's verifying key is published in the territories docs; it is a public key, safe to embed in any app; self-host operators generate their own key pair with snfactory keygen and pin their own public key, which is exactly what makes a deployment yours: it runs entirely on your infrastructure.

The web SDK streams tiles from the API rather than verifying packages in the browser, so pinning applies to the mobile SDKs.

Licensing: per vehicle or per MAU

The on-device SDK is licensed per vehicle per month for fleets. If you are building an app rather than running a fleet, the same SDKs can be metered per monthly active user instead: your app sends an opaque X-MapMap-User header on its gateway requests (8–128 printable ASCII characters; hash an install id; never send PII, and the gateway hashes the value again before storing it), and the gateway counts distinct identifiers per calendar month. No header means no MAU counting, which is the normal state for server-to-server API use. The SDKs do not yet set this header automatically; send it from your app's networking layer:

sh
curl -fsS -H "Authorization: Bearer $API_KEY" \
  -H "X-MapMap-User: 9f2c4a1e8b7d3f60" \
  "$BASE/route/v1/truck/1.3134,51.1279;-1.8904,52.4862"

Billing is fail-open by design: when a new user cannot be covered by your prepaid balance the request is never refused; the account is marked mau_overdrawn for the month (visible on GET /v1/keys/self) and the gateway keeps serving, so your users are never interrupted by your account's billing state. Numbers on pricing.

Next steps

  • Android API reference: every public class and method of ai.mapmap:core
  • Vehicle avatars: draw the vehicle as a MapMap car, on the web or from the hosted sprites
  • File formats: channel index, package layout, .drive.jsonl replay corpus
  • Quickstart: issue an snk_ key and route a truck in two calls
  • Conventions: base URL, auth, error envelope, ADR tunnel codes
  • Playground: try routing with zero install
  • Self-host: run the gateway and map factory yourself