Skip to content

MLMap

Defined in: packages/core/src/components/ml-map.ts:431

MLMap custom element for rendering MapLibre maps from YAML/JSON configuration.

Dispatched on the element as CustomEvents; listen with addEventListener.

EventWhen
ml-map:loadMap loaded and ready for interaction
ml-map:errorError during initialization or runtime
ml-map:loadingLoading configuration from URL
ml-map:layer-addedLayer was added to the map
ml-map:layer-removedLayer was removed from the map
ml-map:layer-data-loadingLayer data is being fetched
ml-map:layer-data-loadedLayer data loaded successfully
ml-map:layer-data-errorLayer data failed to load
ml-map:layer-clickUser clicked on a layer feature
ml-map:layer-hoverUser hovered over a layer feature
ml-map:markers-addedStandalone markers: pins were added
ml-map:marker-clickUser clicked a standalone marker
ml-map:marker-icon-errorA marker icon failed (unsafe scheme or load error); the default pin was substituted
ml-map:image-errorA declared images: entry failed (unsafe scheme, load or register error)
ml-map:parameter-changeA params-panel control wrote a state key
ml-map:layer-visibilityA params-panel checkbox toggled a layer
ml-map:camera-fitThe fitTo camera framed its source’s data (detail: source, bounds)
ml-map:layer-classifiedA classify: layer’s classes as drawn (detail: layerId, classify), on load and when fetched data (re)computes them
ml-map:update-appliedA changed document was applied to the running map (detail: summary; summary.rebuild when a basemap change rebuilt it)
ml-map:update-rejectedA changed document was refused and the running map kept (detail: kind, errors)
ml-map:state-changeThe document’s state: values changed (detail: values, changed)
ml-map:source-loadedA type: grid source was decoded and getGrid(sourceId) answers: on the first load and after every swap (detail: sourceId)
  • BaseElement

new MLMap(): MLMap

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.dom.d.ts:13847

MLMap

BaseElement.constructor

static fitToWaitMs: number = 1500

Defined in: packages/core/src/components/ml-map.ts:509

How long <ml-map> waits for a fitTo source’s data before it builds the map anyway, in milliseconds (ml-aot.75).

When config.fitTo names a url: GeoJSON source, the element fetches that file as soon as the document is read and builds the map with the data’s bounds, so the first frame is already framed — no load at the authored center/zoom followed by a jump. If the file takes longer than this, the map is built at the authored center/zoom and jumps once the data lands (the 0.8 behaviour); the file is still requested only once. Set it before maps render (MLMap.fitToWaitMs = 3000); 0 turns the wait off.

get base(): string | null

Defined in: packages/core/src/components/ml-map.ts:629

Where the site paths in this map start: the path a site is deployed under, such as "/my-repo/" for a GitHub Pages project site. Reflects the base attribute; null when unset.

With a base, every path to a file of your own — the src attribute and, inside the document, source url/tiles/data, images:, marker icon:, mapStyle and popup links — resolves against it: /data/x.geojson and data/x.geojson both load /my-repo/data/x.geojson, on every page of the site. A path that already starts with the base is used as written, and full URLs (https://…, //cdn…, blob:, data:) are never changed. Without a base, relative paths resolve against the page and /… against the domain root, as before. The Astro components set it from import.meta.env.BASE_URL. Changing it re-renders the map.

string | null

set base(value): void

Defined in: packages/core/src/components/ml-map.ts:633

ParameterType
valuestring | null

void


get camera(): MLMapCameraOwner

Defined in: packages/core/src/components/ml-map.ts:696

Who owns the camera when the document changes (live documents, KTD13). Reflects the camera attribute: document (the default) or host.

document: a changed center, zoom, bearing or pitch eases the map there, an added or re-targeted fitTo frames its source once, and a basemap change rebuilds at the current camera unless the document’s camera changed. host: an update never moves the camera and a rebuild always keeps the current one — for a page whose viewport is per-user. Hosts that want the document camera re-applied on every update do it themselves on ml-map:update-applied.

MLMapCameraOwner

set camera(value): void

Defined in: packages/core/src/components/ml-map.ts:700

ParameterType
valueMLMapCameraOwner

void


get config(): {[key: string]: any; } | null

Defined in: packages/core/src/components/ml-map.ts:713

Get the current map configuration

While document text is being read (a TOML document waits for its reader), this is still the last document applied; text assigned before the element connects reads as null until it has been read.

{[key: string]: any; } | null

set config(value): void

Defined in: packages/core/src/components/ml-map.ts:734

Set the map configuration programmatically.

Accepts a MapBlock object or document text in YAML, JSON or TOML; both are validated like every other config path, whether assigned before or after the element connects. Text reads with positions, and a duplicate JSON key is an error. Assigning a value that is JSON-equal to the config currently applied, or the same text again, is a no-op, so a framework re-binding an equal object does not touch the map. A different document is applied to the running map in place (live documents, 0.10): the camera stays unless the document’s camera changed, getMap() keeps its identity, and ml-map:update-applied reports what changed; a document that fails validation is refused with ml-map:update-rejected and the map untouched; a mapStyle change rebuilds the map at the current camera. Assigning null clears the stored config without touching a rendered map.

ParameterType
valuestring | {[key: string]: any; } | null

void


get debug(): boolean

Defined in: packages/core/src/components/ml-map.ts:675

Whether author hints show on the page wherever it is served. Reflects the boolean debug attribute.

The on-page notice always lists failures (a data file that didn’t load, a layer MapLibre rejected). Author hints — did-you-mean suggestions, a key nested under config:, a fitTo typo, coordinates that look swapped, a string starting with the reserved = — show only while you develop: on a page served from this computer (localhost and *.localhost, 127.x, [::1], a dev server bound to every interface opened at 0.0.0.0 or [::], file:) and in a bundler dev build (astro dev, vite). debug shows them on a published site too, for checking a deploy. quiet still wins: it hides the notice entirely. The console always gets every hint either way.

boolean

set debug(value): void

Defined in: packages/core/src/components/ml-map.ts:679

ParameterType
valueboolean

void


get quiet(): boolean

Defined in: packages/core/src/components/ml-map.ts:650

Whether on-page notices for NON-fatal problems are suppressed — the “part of this map couldn’t load” notice and the zero-height hint. Reflects the boolean quiet attribute.

For a production page that would rather fail quietly than show authors’ diagnostics to visitors. The problems are still logged to the console and still dispatched as events. The error card for a document that cannot render at all is never suppressed — it replaces a map that is not there.

boolean

set quiet(value): void

Defined in: packages/core/src/components/ml-map.ts:654

ParameterType
valueboolean

void


get static observedAttributes(): string[]

Defined in: packages/core/src/components/ml-map.ts:608

Observed attributes that trigger attributeChangedCallback

string[]

addEventListener<K>(type, listener, options?): void

Defined in: packages/core/src/components/ml-map.ts:2894

Type Parameter
K extends keyof MLMapEventMap
ParameterType
typeK
listener(this, event) => unknown
options?boolean | AddEventListenerOptions

void

BaseElement.addEventListener

addEventListener<K>(type, listener, options?): void

Defined in: packages/core/src/components/ml-map.ts:2899

Type Parameter
K extends keyof HTMLElementEventMap
ParameterType
typeK
listener(this, event) => unknown
options?boolean | AddEventListenerOptions

void

BaseElement.addEventListener

addEventListener(type, listener, options?): void

Defined in: packages/core/src/components/ml-map.ts:2904

ParameterType
typestring
listenerEventListenerOrEventListenerObject
options?boolean | AddEventListenerOptions

void

BaseElement.addEventListener


addLayer(layer): Promise<void>

Defined in: packages/core/src/components/ml-map.ts:2764

Add a layer to the map

ParameterTypeDescription
layeranyLayer configuration object

Promise<void>

Promise that resolves when the layer is added

await mapEl.addLayer({
id: 'new-layer',
type: 'circle',
source: {
type: 'geojson',
data: { type: 'FeatureCollection', features: [] }
},
paint: { 'circle-radius': 6, 'circle-color': '#ff0000' }
});

attributeChangedCallback(name, oldValue, newValue): void

Defined in: packages/core/src/components/ml-map.ts:863

Called when an observed attribute changes

ParameterType
namestring
oldValuestring | null
newValuestring | null

void


connectedCallback(): void

Defined in: packages/core/src/components/ml-map.ts:815

Called when the element is added to the DOM

void


disconnectedCallback(): void

Defined in: packages/core/src/components/ml-map.ts:856

Called when the element is removed from the DOM

void


getDocument(): {[key: string]: any; } | null

Defined in: packages/core/src/components/ml-map.ts:2835

The document the running map shows: the parsed MapBlock, the same shape config returns and update takes (KTD15). null with no running map. The renderer’s getDocument() returns its normalized model instead; neither is the other’s input.

{[key: string]: any; } | null


getGrid(sourceId): GridField | undefined

Defined in: packages/core/src/components/ml-map.ts:2674

A type: grid source’s field (grid source, R14): the decoded, sampleable field once it is in, undefined before that and for any other source. Never mutated: a live update that changes the source hands out a new one, and ml-map:source-loaded says when.

ParameterType
sourceIdstring

GridField | undefined

const field = el.getGrid("elevation");
if (field) readout.textContent = `${field.sample(map.getCenter())} ${field.units}`;

getMap(): maplibregl.Map | null

Defined in: packages/core/src/components/ml-map.ts:2557

Get the underlying MapLibre GL map instance

maplibregl.Map | null

The MapLibre GL map instance, or null if not initialized

MLMap.mapReady — the promise form; resolves once loaded and removes the need for the load-listener + null-guard shown below.

const mapEl = document.querySelector('ml-map');
mapEl.addEventListener('ml-map:load', () => {
const map = mapEl.getMap();
map.flyTo({ center: [-122.4, 37.8], zoom: 14 });
});

getRenderer(): MapRenderer | null

Defined in: packages/core/src/components/ml-map.ts:2732

Get the MapRenderer instance

MapRenderer | null

The MapRenderer instance, or null if not initialized


getState(): Record<string, unknown>

Defined in: packages/core/src/components/ml-map.ts:2856

The document’s current state: values: its defaults, the panel’s seeds and every write since. {} with no running map.

Record<string, unknown>


gridReady(sourceId): Promise<GridField>

Defined in: packages/core/src/components/ml-map.ts:2709

Resolve with a type: grid source’s field once it is decoded (R14), at once if it already is. Separate from mapReady: the map opens without waiting for its grids, and this does not wait for the layers. Rejects when the applied document has no grid source of that id, when its file fails to load (the map’s notice says why; a later reload() gives new callers a fresh promise) and when the source is removed. Called before the map exists it waits for the map to load and asks then; across a basemap rebuild (KTD8) it answers from the map that took over, the way mapReady() resolves with that map.

ParameterType
sourceIdstring

Promise<GridField>

const field = await document.querySelector("ml-map").gridReady("elevation");
const metres = field.sample({ lng: 10, lat: 45 });

hasGrid(sourceId): boolean

Defined in: packages/core/src/components/ml-map.ts:2688

Whether the applied document has a type: grid source of this id, decoded or not — so getGrid() returning undefined can be read as “not yet” rather than “no such source”. False before the map has loaded.

ParameterType
sourceIdstring

boolean

if (el.hasGrid("elevation") && !el.getGrid("elevation")) readout.textContent = "Loading…";

isLoaded(): boolean

Defined in: packages/core/src/components/ml-map.ts:2741

Check if the map is loaded

boolean

True if the map has finished loading


mapReady(): Promise<maplibregl.Map>

Defined in: packages/core/src/components/ml-map.ts:2600

Resolve with the underlying MapLibre map once the document has loaded.

Promise<maplibregl.Map>

The readiness idiom (R3): replaces the ml-map:load listener + getMap() null-guard boilerplate every page-code snippet needed. Resolves immediately when the map is already loaded; otherwise resolves on the next ml-map:load and rejects on ml-map:error (config parse failure, renderer construction failure, or a runtime map error).

const map = await document.querySelector('ml-map').mapReady();
map.flyTo({ center: [-122.4, 37.8], zoom: 14 });

reload(): Promise<void>

Defined in: packages/core/src/components/ml-map.ts:2874

Reload configuration from the current source

Promise<void>

Promise that resolves when reload is complete

Re-fetches src (or re-reads the inline script, or the config attribute) and applies the result to the running map as an update (KTD11): sources whose last load failed are retried even when the document is unchanged, and so is a TOML reader that couldn’t be downloaded. From an error card, a valid document renders fresh.


removeEventListener<K>(type, listener, options?): void

Defined in: packages/core/src/components/ml-map.ts:2909

Type Parameter
K extends keyof MLMapEventMap
ParameterType
typeK
listener(this, event) => unknown
options?boolean | EventListenerOptions

void

BaseElement.removeEventListener

removeEventListener<K>(type, listener, options?): void

Defined in: packages/core/src/components/ml-map.ts:2914

Type Parameter
K extends keyof HTMLElementEventMap
ParameterType
typeK
listener(this, event) => unknown
options?boolean | EventListenerOptions

void

BaseElement.removeEventListener

removeEventListener(type, listener, options?): void

Defined in: packages/core/src/components/ml-map.ts:2919

ParameterType
typestring
listenerEventListenerOrEventListenerObject
options?boolean | EventListenerOptions

void

BaseElement.removeEventListener


removeLayer(layerId): void

Defined in: packages/core/src/components/ml-map.ts:2773

Remove a layer from the map

ParameterTypeDescription
layerIdstringID of the layer to remove

void


setLayerVisibility(layerId, visible): void

Defined in: packages/core/src/components/ml-map.ts:2783

Set layer visibility

ParameterTypeDescription
layerIdstringID of the layer
visiblebooleanWhether the layer should be visible

void


setState(values): void

Defined in: packages/core/src/components/ml-map.ts:2849

Write state: values (live documents, R12): each goes through the map’s global state, the params panel follows, and one ml-map:state-change fires. Declared keys only: an undeclared key refuses the whole call. During a basemap rebuild the values land on the new map once it loads.

ParameterType
valuesRecord<string, unknown>

void

With no running map, for an undeclared key, or on a maplibre-gl without setGlobalStateProperty (below 5.6).


uiString(key, params?): string

Defined in: packages/core/src/components/ml-map.ts:2580

One of the UI strings for this map: the document’s locale: entry for key, else the English default.

ParameterType
key"maplibre-yaml.Legend.Title" | "maplibre-yaml.Notice.Title" | "maplibre-yaml.Notice.HintsTitle" | "maplibre-yaml.Notice.AuthorDetails" | "maplibre-yaml.Notice.Dismiss" | "maplibre-yaml.Notice.More" | "maplibre-yaml.Notice.ZoomIn" | "maplibre-yaml.ErrorCard.HowToFix" | "maplibre-yaml.ErrorCard.ConfigurationError" | "maplibre-yaml.ErrorCard.MapError" | "maplibre-yaml.ErrorCard.StyleNotLoaded" | "maplibre-yaml.ErrorCard.StyleHint" | "maplibre-yaml.ErrorCard.LocalServer" | "maplibre-yaml.ErrorCard.LocalServerHint" | "maplibre-yaml.Loading" | "maplibre-yaml.HeightHint" | "maplibre-yaml.Params.StateUnsupported" | "maplibre-yaml.Story.Chapters" | "maplibre-yaml.Story.GoToChapter" | "maplibre-yaml.Story.ImageMissing" | "maplibre-yaml.Story.VideoMissing" | "maplibre-yaml.Story.MediaMissingHint" | "maplibre-yaml.Story.VideoUnsupported" | "maplibre-yaml.Classify.NoData" | "maplibre-yaml.Classify.Other" | "maplibre-yaml.FullPageMap.ResetView" | "Map.Title" | "NavigationControl.ZoomIn" | "NavigationControl.ZoomOut"
params?StringParams

string

For hosts that draw their own chrome next to the map (slot content, Astro’s <FullPageMap> buttons) and want it in the map’s language. Takes maplibre-yaml keys (maplibre-yaml.Legend.Title, …) and the MapLibre keys the library reads (Map.Title, NavigationControl.ZoomIn, NavigationControl.ZoomOut). English until a document has been read.

const el = document.querySelector("ml-map");
await el.mapReady();
button.ariaLabel = el.uiString("NavigationControl.ZoomIn"); // "Zoom in", or its translation

update(doc): Promise<UpdateResult>

Defined in: packages/core/src/components/ml-map.ts:2818

Apply a new document to the running map (live documents, 0.10): the method form of assigning config.

ParameterType
docstring | {[key: string]: any; }

Promise<UpdateResult>

Takes a MapBlock or document text (YAML, JSON or TOML), validates it like every other path, and resolves when the outcome is final: applied with the summary of what changed (ml-map:update-applied fired), rejected with the diagnostics (ml-map:update-rejected fired, map untouched), fallback when a basemap change rebuilt the map or there was no running map yet, or superseded when a later document replaced this one before it applied (a TOML document still waiting for its reader included). A document equal to the applied one resolves applied with nothing in the summary. Text that is TOML when the TOML reader can’t be downloaded is refused with kind: "chunk", the map untouched.

const { outcome, summary } = await el.update({ ...el.getDocument(), layers });

updateLayerData(layerId, data): void

Defined in: packages/core/src/components/ml-map.ts:2793

Update layer data

ParameterTypeDescription
layerIdstringID of the layer
dataGeoJSONNew GeoJSON data

void