--- url: /reference/items/MapboxMap/js-api.md --- # JS API This page documents thirteen components — a single root component, `MapboxMap`, which owns the Mapbox `Map` instance, plus the twelve children below — built on the `AbstractMapboxMapChild` (and, for controls, `AbstractMapboxControl`) base classes. The [`StoreLocator`](/reference/items/StoreLocator/) orchestrator completes the family on its own page. Every map child resolves the closest parent `MapboxMap` on its own and registers itself against its map once it is loaded. `MapboxClusterItem` is the one exception: it is a rendered list element that extends `Base` directly, and resolves the closest `MapboxCluster` instead of a map. [Register](/guide/usage/#registering-components) each component you use — ideally through a lazy [manifest](/guide/autoloading/) entry so the heavy `mapbox-gl` dependency stays out of your main bundle (see [Lazy loading](/reference/items/MapboxMap/#lazy-loading)). * **[Map](#map)** — `MapboxMap` * **[Markers & Popups](#markers-popups)** — `MapboxMarker`, `MapboxPopup` * **[Controls](#controls)** — `MapboxNavigationControl`, `MapboxGeolocateControl`, `MapboxFullscreenControl`, `MapboxGeocoder` * **[Data](#data)** — `MapboxSource`, `MapboxLayer`, `MapboxImage`, `MapboxImages` * **[Cluster](#cluster)** — `MapboxCluster`, `MapboxClusterItem` (see also the [`StoreLocator`](/reference/items/StoreLocator/) orchestrator) * **[AbstractMapboxMapChild](#abstractmapboxmapchild)** — the shared base class ## Providing the `mapbox-gl` dependency By default the components resolve `mapbox-gl` (and the optional `@mapbox/mapbox-gl-geocoder`) with a lazy `import()` the first time a map is built, so nothing needs configuring — keep `mapbox-gl` installed and it just works, staying out of your main bundle until a map is on the page. To control which `mapbox-gl` the components use — a pinned version, a self-hosted build (for example a same-origin worker under a strict CSP), or a module served from an import map or a CDN — inject your own instance once, before the components mount: ```js import mapboxgl from 'mapbox-gl'; import MapboxGeocoder from '@mapbox/mapbox-gl-geocoder'; import { provideMapboxGl, provideMapboxGeocoder } from '@studiometa/ui-mapbox'; provideMapboxGl(mapboxgl); provideMapboxGeocoder(MapboxGeocoder); // optional geocoder peer ``` Once provided, `@studiometa/ui-mapbox` never imports `mapbox-gl` by specifier — it uses the instance you handed it. `resolveMapboxGl()` and `resolveMapboxGeocoder()` are exported too if you want to trigger and await resolution yourself (for example to preload the module). ## Reactivity and updates To move the map, change its data or update a marker after mount, reach for the underlying Mapbox objects directly through the component instances: ```js import { getInstance } from '@studiometa/js-toolkit'; // The Mapbox `Map` instance is exposed on the `MapboxMap` component. const mapboxMap = getInstance(element, MapboxMap); mapboxMap.map.setCenter([2.35, 48.86]); mapboxMap.map.setZoom(12); // Markers, popups and sources expose their own Mapbox object too. marker.marker.setLngLat([2.29, 48.86]); ``` Every component documents the Mapbox object it exposes (`map`, `marker`, `popup`, `control`, …) in its **Getters** section below. ::: tip Switching base style keeps your layers Calling `map.setStyle(…)` wipes the entire style — every source, layer and sprite — while the map instance and the still-mounted child components survive. Each map child subscribes to the map's `style.load` and **re-injects** its contribution automatically, so your declarative sources, layers, images and clusters re-appear on the new base style instead of silently vanishing. You can switch the base style at runtime without re-declaring your data. ::: ## Map ### MapboxMap Display an interactive Mapbox GL map. This is the root component of the system and the parent of every other component. It instantiates the Mapbox `Map` lazily and re-emits its events. #### Options ##### `access-token` * Type: `String` Mapbox GL [access token](https://docs.mapbox.com/help/getting-started/access-tokens/) (required). ##### `zoom` * Type: `Number` Initial zoom level. ##### `center` * Type: `Array` * Default: `[0, 0]` Initial center as `[longitude, latitude]`. ##### `map-options` * Type: `Object` * Default: `{}` Any other [Mapbox `Map` option](https://docs.mapbox.com/mapbox-gl-js/api/map/#map-parameters), spread into the constructor. This is where `style`, `pitch`, `bearing`, `bounds`, … go. The `access-token`, `zoom` and `center` options act as overridable defaults, then `map-options` is spread into the [Mapbox `Map` constructor](https://docs.mapbox.com/mapbox-gl-js/api/map/#map-parameters). The `container` is always resolved from the component (the `container` ref, falling back to the root element) and can not be overridden. Use `map-options` for anything the convenience options above do not cover — most notably the map [`style`](https://docs.mapbox.com/mapbox-gl-js/api/map/#map-parameters): ```html
``` #### Refs ##### `container` * Type: `HTMLElement` The element used as the map container. Falls back to the root element when omitted. #### Getters ##### `map` * Type: `mapboxgl.Map | undefined` The underlying Mapbox GL map instance, or `undefined` until it has been built. The map is created in `mounted()`, after `mapbox-gl` resolves — it may be injected or lazily imported — so a caller should either wait for the `map-load` event or go through [`whenMapReady()`](#whenmapready-callback). ##### `isLoaded` * Type: `boolean` Whether the map has finished loading (a public field, not a getter). #### Events The component emits a custom `map-load` event, plus all the common Mapbox GL map events prefixed with `map-` to avoid conflicts with native events. Every payload is a named object: `map-load` carries `{ map }`, and every forwarded event carries the Mapbox event object as `{ event }`. ##### `map-load` * Payload: `{ map }` The map finished loading (custom event). ##### `map-idle` The map is idle after rendering. ##### `map-render` A frame is rendered. ##### `map-resize` The map container is resized. ##### `map-remove` The map is removed. ##### `map-error` An error occurred, carrying the Mapbox error event as `{ event }`. Not to be confused with the map children's own `map-error`, which carries `{ error }` — both bubble, so an ancestor listening for `map-error` should read the payload by component. ##### `map-click` A click on the map. ##### `map-dblclick` A double-click on the map. ##### `map-mouseenter` The pointer enters the map canvas. ##### `map-mouseleave` The pointer leaves the map canvas. ##### `map-mousemove` The pointer moves over the map. ##### `map-movestart` Map movement starts (pan, zoom, rotate). ##### `map-move` The map is moving. ##### `map-moveend` Map movement ends. ##### `map-zoomstart` A zoom transition starts. ##### `map-zoom` The zoom level changes. ##### `map-zoomend` A zoom transition ends. ##### `map-rotatestart` Rotation starts. ##### `map-rotate` The map is rotating. ##### `map-rotateend` Rotation ends. ##### `map-pitchstart` A pitch transition starts. ##### `map-pitch` The pitch changes. ##### `map-pitchend` A pitch transition ends. ##### `map-dragstart` A drag starts. ##### `map-drag` The map is being dragged. ##### `map-dragend` A drag ends. Listen to these events from a parent component with `on` methods: ```js import { Base, registerComponent } from '@studiometa/js-toolkit'; import { MapboxMap } from '@studiometa/ui-mapbox'; class App extends Base { static config = { name: 'App', components: { MapboxMap }, }; onMapboxMapMapLoad({ payload: { map } }) { console.log('Map is ready', map); } onMapboxMapMapClick({ payload: { event } }) { console.log('Clicked at', event.lngLat); } onMapboxMapMapZoomend({ payload: { event } }) { console.log('New zoom level', event.target.getZoom()); } } registerComponent(App); ``` ## Markers & Popups ### MapboxMarker Add a [marker](https://docs.mapbox.com/mapbox-gl-js/api/markers/#marker) to the map. A `MapboxPopup` nested inside the marker is automatically attached to it. #### Options ##### `lng-lat` * Type: `Array` * Default: `[0, 0]` Marker position as `[longitude, latitude]`. ##### `marker-options` * Type: `Object` * Default: `{}` [Mapbox Marker options](https://docs.mapbox.com/mapbox-gl-js/api/markers/#marker) (color, anchor, draggable, …). #### Getters ##### `marker` * Type: `mapboxgl.Marker` The underlying Marker instance. ##### `popup` * Type: `MapboxPopup` The first nested `MapboxPopup` child, if any. #### Methods ##### `setChildPopup(popup)` * Arguments: `MapboxPopup` Attach a child `MapboxPopup`'s popup to this marker. It is called automatically by whichever of the two mounts last — the marker pulls its child popup once the map is ready, and a popup that mounts after its marker (a dynamic append) pushes itself here. Setting the same popup twice is idempotent. ### MapboxPopup Display a [popup](https://docs.mapbox.com/mapbox-gl-js/api/markers/#popup) on the map. It can be used standalone (placed directly on the map at a given position) or nested inside a `MapboxMarker` (attached to the marker, no `lng-lat` needed). The popup content is taken from the element's inner HTML. #### Options ##### `lng-lat` * Type: `Array` * Default: `[0, 0]` Popup position as `[longitude, latitude]` (standalone popups only). ##### `popup-options` * Type: `Object` * Default: `{}` [Mapbox Popup options](https://docs.mapbox.com/mapbox-gl-js/api/markers/#popup). #### Getters ##### `popup` * Type: `mapboxgl.Popup` The underlying Popup instance. ## Controls All controls extend [`AbstractMapboxMapChild`](#abstractmapboxmapchild) and expose the underlying Mapbox control through a `control` getter. They share a `position` option and are added to the map on mount, removed on unmount. `MapboxGeocoder` is the exception: it has no `position` option, and it can render in its own element, with or without a map. ### MapboxNavigationControl Add zoom in/out and compass controls to the map. #### Options ##### `position` * Type: `String` * Default: `'top-right'` Control position: `top-left`, `top-right`, `bottom-left` or `bottom-right`. ##### `show-compass` * Type: `Boolean` * Default: `false` Show the compass button. ##### `show-zoom` * Type: `Boolean` * Default: `false` Show the zoom in/out buttons. ##### `visualize-pitch` * Type: `Boolean` * Default: `false` Visualize the pitch on the compass button. ### MapboxGeolocateControl Add a button that uses the browser's geolocation API to locate the user on the map. #### Options ##### `position` * Type: `String` * Default: `'top-right'` Control position. ##### `position-options` * Type: `Object` Browser [`PositionOptions`](https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions). ##### `fit-bounds-options` * Type: `Object` [`FitBoundsOptions`](https://docs.mapbox.com/mapbox-gl-js/api/map/#map#fitbounds) used when tracking. ##### `track-user-location` * Type: `Boolean` * Default: `false` Continuously track the user location. ##### `show-accuracy-circle` * Type: `Boolean` * Default: `false` Show the accuracy circle around the user location. ##### `show-user-location` * Type: `Boolean` * Default: `false` Show the user location dot. ##### `show-user-heading` * Type: `Boolean` * Default: `false` Show the user heading indicator. ### MapboxFullscreenControl Add a button that toggles the map fullscreen. #### Options ##### `position` * Type: `String` * Default: `'top-right'` Control position. ### MapboxGeocoder Add an address search control powered by [`@mapbox/mapbox-gl-geocoder`](https://github.com/mapbox/mapbox-gl-geocoder). Install the optional `@mapbox/mapbox-gl-geocoder` peer dependency to use it. ::: tip Optional, loaded on demand `@mapbox/mapbox-gl-geocoder` is an optional peer dependency. It is loaded lazily with a dynamic `import()` when a `MapboxGeocoder` mounts, so the rest of the package works without it installed. If you use this component, add it to your project: `npm install @mapbox/mapbox-gl-geocoder`. With autoloading, `MapboxGeocoder` uses the `visible` mount strategy, so it mounts and loads the library when its element nears the viewport. Do not put `hidden` on its element: a hidden element never does. Use `data-mount="eager"` to load it without waiting for the viewport. ::: #### Options ##### `access-token` * Type: `String` Mapbox [access token](https://docs.mapbox.com/help/getting-started/access-tokens/) for the geocoding requests. Inside a `MapboxMap`, the geocoder uses the map's `access-token` when this option is not set. Without a parent map, the geocoder needs it (see [Standalone usage](#standalone-usage)). The token is taken from the first of these that is set: 1. `accessToken` in the `options` option. 2. The `access-token` option. 3. The `access-token` of the parent `MapboxMap`. This is the same order as on `MapboxMap`, where an `accessToken` in [`map-options`](#map-options) wins over its `access-token` option. ##### `add-to-map` * Type: `Boolean` * Default: `false` Add the geocoder to the map as a control. This requires a parent `MapboxMap`. Otherwise it is rendered inside the component's element, with or without a parent map (see [Standalone usage](#standalone-usage)). ##### `options` * Type: `Object` * Default: `{}` [Geocoder options](https://github.com/mapbox/mapbox-gl-geocoder/blob/master/API.md#parameters). Non-serializable options (`filter`, `externalGeocoder`, `render`, `getItemValue`, `localGeocoder`) are not supported. An `accessToken` set in `options` wins over the geocoder's `access-token` option. Prefer the `access-token` option: it keeps the token out of the JSON. #### Getters ##### `control` * Type: `MapboxGeocoderControl | undefined` The underlying `mapbox-gl-geocoder` control instance. It is created once the lazily imported geocoder module resolves, so it is `undefined` until then. ##### `target` * Type: `Map | HTMLElement | string` Where the control is mounted, depending on `add-to-map`. #### Events ##### `map-result` * Payload: `{ result }` Emitted when the geocoder resolves an address, carrying the geocoder's selected feature. #### Standalone usage The geocoder does not need a map. Without `add-to-map` and without an ancestor element declared as `MapboxMap`, the component works on its own: it creates the control on mount, adds the search input to its own root element and emits `map-result` with the selected feature. Use it for an address search that drives something other than a map, such as a search form. A standalone geocoder has no map to read the access token from, so set its `access-token` option. Without a token, the component logs a `mapbox-geocoder.missing-access-token` warning and does not create the control. A standalone geocoder does not load `mapbox-gl`. The following example fills a hidden `near` field with the coordinates of the selected address, then submits a [`Fetch`](/reference/items/Fetch/) form. An [`Action`](/reference/items/Action/) on the same element listens to `map-result`. The field stays disabled until an address is selected, so the form never sends an empty `near` parameter. ```html
…
``` Inside a `MapboxMap`, the geocoder uses the map, even when the map mounts after it: the access token falls back to the map's [`access-token`](#access-token). Only a geocoder added to the map with [`add-to-map`](#add-to-map) shows a marker for the result and moves the map: a geocoder rendered in its own element never does, with or without a parent map. In a [`StoreLocator`](/reference/items/StoreLocator/), the geocoder can also be placed outside the `MapboxMap` element, anywhere inside the `StoreLocator` element. It then works standalone and needs its own `access-token`, and the `StoreLocator` still frames the map on its `map-result` event. ## Data ### MapboxSource Add a [source](https://docs.mapbox.com/style-spec/reference/sources/) to the map. On unmount, every layer tied to the source is removed before the source itself. #### Options ##### `id` * Type: `String` Unique source id, referenced by layers. ##### `source` * Type: `Object` A [source specification](https://docs.mapbox.com/style-spec/reference/sources/), e.g. `{ "type": "geojson", "data": … }`. #### Refs ##### `geojson` * Type: `HTMLScriptElement` Optional `