Skip to content

Export to style.json

An export turns a map document into a standalone MapLibre style.json: the basemap, your sources and your layers in one file. The file renders with plain maplibre-gl, opens in Maputnik, and works in any app that reads MapLibre styles, with no maplibre-yaml on the page. The CLI command that exports is mlym emit.

  1. In the folder with your map.yaml, export it:

    Terminal window
    npx maplibre-yaml@latest emit map.yaml --out dist/

    This writes dist/style.json. A warning on the terminal names each part of the document that a style can’t hold, such as popups or controls.

  2. Next to map.yaml, create plain.html, a page with maplibre-gl and nothing else:

    <!doctype html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Exported map</title>
    <link rel="stylesheet" href="https://unpkg.com/maplibre-gl@6/dist/maplibre-gl.css">
    <style>
    body { margin: 0; }
    #map { height: 100vh; }
    </style>
    </head>
    <body>
    <div id="map"></div>
    <script type="module">
    import * as maplibregl from "https://unpkg.com/maplibre-gl@6/dist/maplibre-gl.mjs";
    new maplibregl.Map({ container: "map", style: "dist/style.json" });
    </script>
    </body>
    </html>
  3. Serve the folder with npx serve . and open /plain at the address it prints.

You see your map: the basemap and your layers, drawn by maplibre-gl alone. Clicking a feature does nothing, because a style can’t hold behaviour. To get popups and hover back, see Keep the interactions.

A MapLibre style holds sources, layers, the camera and the basemap. It has no way to say “open a popup on click” or “show a legend”, so those parts of a document are left out, each with a contract warning. mlym emit also does the work a plain style can’t do at run time:

  • it merges the basemap into the style;
  • it writes the breaks a classify: layer computes from its data;
  • it turns markers into a symbol layer with pin images, and fitTo into a fixed camera, each with a lossy warning;
  • it converts or rewrites large-data files.

Export classes lists what happens to every part of a document. --strict refuses an export with any lossy warning, for CI, and emit lists every option.

attachInteractions puts a document’s popups, hover, camera moves and highlight back onto any maplibre-gl map, including one showing an exported style. It reads them from the same YAML document. This version of plain.html loads the exported style, then attaches the interactions from map.yaml:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Exported map with interactions</title>
<link rel="stylesheet" href="https://unpkg.com/maplibre-gl@6/dist/maplibre-gl.css">
<style>
body { margin: 0; }
#map { height: 100vh; }
</style>
<script type="importmap">
{ "imports": { "maplibre-gl": "https://unpkg.com/maplibre-gl@6/dist/maplibre-gl.mjs" } }
</script>
</head>
<body>
<div id="map"></div>
<script type="module">
import * as maplibregl from "maplibre-gl";
import {
YAMLParser,
normalizeMapBlock,
projectInteractions,
attachInteractions,
} from "https://esm.sh/@maplibre-yaml/core@0.10?external=maplibre-gl";
const map = new maplibregl.Map({ container: "map", style: "dist/style.json" });
// The interactions come from the document the style was exported from.
const source = await (await fetch("map.yaml")).text();
const parsed = YAMLParser.safeParseMapBlock(source);
if (!parsed.success) throw new Error(parsed.errors[0].message);
const projection = projectInteractions(normalizeMapBlock(parsed.data));
attachInteractions(map, projection);
</script>
</body>
</html>

Now a click on a feature opens its popup. The import map makes the library use the same maplibre-gl as the page; the JavaScript API page explains that setup.

  • projectInteractions(model) reads the interactions out of a document as plain data.
  • attachInteractions(map, projection, options?) binds them to the map’s layers by layer id, and returns a handle: resetFeatureState(layerId) clears hover state after you replace a layer’s data, detach(layerId) removes one layer’s listeners, and destroy() removes all of them and any open popup.
  • hover.highlight needs feature ids, as it does under <ml-map>: set promoteId (or generateId: true) on the source.

The map can also be one your own code built, with its own sources and layers: the interactions bind to whichever layers have the ids the document names. A runnable version is examples/vanilla/export-and-attach.html in the repository.

click.emit is an interaction, not the export command. On a click it calls a function your page registered, with a payload read from the clicked feature:

interactive:
click:
emit:
event: select-quake
payload:
id: { property: code }
place: { property: place }

It fires only through attachInteractions, and only when the page trusts the document and has a handler for the event. Both calls take the trusted policy:

const projection = projectInteractions(model, { trust: "trusted" });
attachInteractions(map, projection, {
policy: { trust: "trusted" },
hostHandlers: {
"select-quake": (payload) => console.log(payload.id, payload.place),
},
});

Without the trusted policy, or without a handler of that name, nothing happens. Under <ml-map> a click.emit never fires: listen for the element’s ml-map:layer-click event instead. The payload rules (str, property, else) are in Popups › Host events.

A style.json can carry a URL but not a file reader, so the large-data formats export like this:

  • PMTiles sources export as pmtiles:// URLs (a .pmtiles URL gains the scheme). The style then needs a renderer that reads pmtiles://, such as maplibre-gl JS with the protocol registered. With a bundler, after npm install pmtiles:

    import maplibregl from "maplibre-gl";
    import { Protocol } from "pmtiles";
    maplibregl.addProtocol("pmtiles", new Protocol().tile);

    In a plain HTML page, import addProtocol from the maplibre-gl your import map names and Protocol from https://esm.sh/pmtiles@4 (esm.sh resolves its dependencies; unpkg does not), before the map is created.

  • A Protomaps basemap (mapStyle: { pmtiles: … }) exports as the full style it generates: every layer, the file as pmtiles://…, and the glyph and sprite URLs. It needs the same pmtiles registration. A relative file path is written as it is, so it resolves against whichever page loads the style; give a full URL for a style used anywhere else. Labels are in lang: (English when unset: an exported style has no page language to follow).

  • FlatGeobuf and GeoParquet sources are converted: mlym emit reads the file (next to the YAML, in the current folder or its public/, or over http(s)) and writes its features into the style as GeoJSON; for GeoParquet, every column, or the columns: you listed. If it can’t read the file, the source is exported empty and reported, and --strict refuses.

  • COG sources export as cog:// URLs, in the form the map itself uses: #dem on an elevation source, a colorRamp: written out as the COG protocol’s #color: fragment, and tileSize: 256. The style then needs the protocol from @geomatico/maplibre-cog-protocol. With a bundler, after npm install @geomatico/maplibre-cog-protocol:

    import maplibregl from "maplibre-gl";
    import { cogProtocol } from "@geomatico/maplibre-cog-protocol";
    maplibregl.addProtocol("cog", cogProtocol);

    In a plain HTML page, load the plugin’s browser build (<script src="https://unpkg.com/@geomatico/maplibre-cog-protocol@0.10/dist/index.js"></script>, which defines MaplibreCOGProtocol) and call addProtocol("cog", MaplibreCOGProtocol.cogProtocol) on the maplibre-gl your import map names, before the map is created.

Export classes lists how every construct exports.

A style can’t hold them. Attach them from the document with attachInteractions.

The export stops with “Sprite assets need an absolute URL”

Section titled “The export stops with “Sprite assets need an absolute URL””

The document has markers or images:, and the exported style needs a full URL for their sprite files. Pass the address the style’s folder will be served from:

Terminal window
npx maplibre-yaml@latest emit map.yaml --out dist/ --sprite-base https://maps.example.org/dist/

The exported style uses pmtiles:// or cog:// URLs. Register the protocol on the page before the map is created (Large-data files).

Something in the document changes what the map shows when exported: the refusal names each part. Export without --strict to accept the fallbacks, or change the document; Reading the report explains the warnings.

projectStyle does the core step of an export in your own code, in Node or in a browser. It is narrower than mlym emit: it doesn’t load data at export (so no computed classify: breaks or converted files), and it doesn’t write sprite files for markers. In a Node script:

import { readFileSync } from "node:fs";
import {
YAMLParser,
normalizeMapBlock,
projectStyle,
resolveBasemap,
mergeBasemap,
} from "@maplibre-yaml/core";
const parsed = YAMLParser.safeParseMapBlock(readFileSync("map.yaml", "utf8"));
if (!parsed.success) throw new Error(parsed.errors[0].message);
const model = normalizeMapBlock(parsed.data);
// The style half of the document; projected.warnings names each part left out.
const projected = projectStyle(model, "with-fallbacks");
// Merge the basemap: a style URL (fetched), an inline style, or a Protomaps
// file (generated).
const basemap = model.style.basemap;
const { style } = basemap
? mergeBasemap(await resolveBasemap(basemap), projected)
: projected;

style is the style object; pass it to new maplibregl.Map({ style }) or write it to a file. normalizeMapBlock reads format v1 and v2 documents alike.

  • Export classes: what happens to each part of a document, and how to read the warnings.
  • emit: every option of the command.
  • Format v2: a layout that keeps what exports under style:.

How to write popups, hover and camera moves is in Popups, hover & controls; every interaction field is in the layer reference.