Skip to content

Public API Overview

This page is the authoritative map of every symbol exported by the Mapsted Maps JavaScript API (latest release 4.0.1). Every method listed here is exported from the API's public entry point. No methods from V2/V3 class-based patterns appear on this page — see V3 → 4.0.1 Migration guide if you need V3 → 4.0.1 rename mappings.


Quick-start

CDN

html
<script src="https://mapi.mapsted.com/v4.0.1/maps.js?id=1234"></script>
<script>
  // mapsted.maps is the namespace injected by the CDN bundle
  await mapsted.maps.init({ element: '#map' });
</script>

npm

js
import * as maps from '@mapsted/maps-js-api';

await maps.init({
  element: '#map',
  propertyId: 1234,
});

Namespace pattern — no class, no default export. The API exports namespace functions (init, selectEntity, etc.) directly. There is no MapstedMapSdk class and no new MapstedMapSdk(...) constructor. See API lifecycle for the full init / destroy flow.


§6.1 Lifecycle (3 methods)

init(options: InitOptions): Promise<MapInstance>

Creates and mounts the map iframe. Required before any other method.

Key InitOptions fields:

FieldRequired (npm)Description
elementyesCSS selector or HTMLElement for the host container
propertyIdyesNumeric Mapsted property ID
mapsDomainyesMaps backend host (e.g. https://maps.mapsted.com)
languagenoBCP 47 tag (e.g. 'en', 'fr-CA')
shareUrlnoBase URL for mobile deep-link share button
strictnotrue → deprecated V2 shim methods throw instead of warn
securitynoSecurityConfig object for multi-origin sandboxing
onloadnoCallback fired synchronously after READY

Resolves with a MapInstance handle ({ destroy, isReady, getState, subscribe }). Throws MAPSTED-1001 if already initialised, MAPSTED-1020 if the container is missing, MAPSTED-1000 if the iframe times out (30 s).

See API lifecycle and Share URL setup.


destroy(): Promise<void>

Tears down the iframe, removes all event listeners, resets state to UNINITIALIZED. init() may be called again after destroy() resolves.


isReady(): Promise<boolean>

Returns true if the API state is READY. Prefer subscribe() for reactive state tracking; use isReady() for one-shot guards.


§6.2 Navigation (6 methods)

Switch the visible floor by its numeric ID. Throws MAPSTED-1012 / MAPSTED-1013 for missing or wrong-type arguments. See Multi-building / floor navigation.


Switch the visible floor by its display name string. See Multi-building / floor navigation.


Move the map to a building, optionally focusing a floor within it. floorId is optional — only buildingId is required. To switch floors of a building already in view, prefer navigateToFloorById / navigateToFloorByName; observe building transitions with the buildingChange event. See Switch between buildings.


setViewport(view: ViewportOptions): Promise<void>

Set the map's zoom level and/or centre. At least one field must be supplied:

FieldTypeConstraint
zoomLevelnumber10 – 24 inclusive
mapCenter[number, number][lng, lat] WGS84; lng ∈ [-180, 180], lat ∈ [-90, 90]

Throws MAPSTED-1043 on out-of-range input. See Set the initial map view.


getFloors(): Promise<FloorInfo[]>

Returns the list of available floors for the loaded property. Each FloorInfo object contains the floor's numeric ID and display name. See Multi-building / floor navigation.


getBuildingInfo(buildingId: number): Promise<BuildingInfo>

Read static building metadata by id: { buildingId, name, entityId, levels }. Useful for populating directory UIs (floor count, building name) without navigating into the building. Throws MAPSTED-1012 / MAPSTED-1013 for invalid input, MAPSTED-1086 when the buildingId is unknown, MAPSTED-1090 before READY.


§6.3 POI / Entity (6 methods)

selectEntity(entityId: MapstedId, options?: SelectOptions): Promise<void>

Highlight and optionally zoom to an entity. MapstedId is string | number.

SelectOptions:

FieldTypeDescription
zoomTonumberZoom level to use when panning to the entity (10–24)
buildingIdnumberRequired for property-level entities; use -1 for property scope
actionTypeActionTypesADD_DESTINATION or ADD_START_POINT for routing
changeFloorbooleanDefault true. Set false to suppress the automatic floor switch when the entity is on a different floor.
panTobooleanDefault true. Set false to suppress the camera recentre on selection. One-shot flag — reverts automatically on the next unqualified select.

Throws MAPSTED-1012 if entityId is null / undefined, MAPSTED-1013 for wrong type. See Select an entity programmatically.


setEntityData(entities: MapEntity[]): Promise<void>

Bulk-set enriched entity data. Each MapEntity can override name, html popup content, a custom marker (image URL or HTML), and a highlight style. See the note in Current public-API scope for the REST entity-catalogue API.


setEntityDataById(id: MapstedId, entity: MapEntity): Promise<void>

Update a single entity by ID without replacing the full set.


setEntityDefaults(defaults: MapEntity): Promise<void>

Set fallback entity fields applied to every entity that does not override them via setEntityData. Throws MAPSTED-1061 if defaults is not a plain MapEntity object.


getEntityData(): Promise<MapEntity[]>

Return all entity data currently held in the API's in-process cache (set via setEntityData or setEntityDataById). Useful for inspecting or serialising the overlay state. The cache uses replace semantics for setEntityData and upsert semantics for setEntityDataById. Throws MAPSTED-1090 if called before READY.


setCoordsData(coords: CoordsData[]): Promise<void>

Attach arbitrary coordinate-based data points to the map for rendering or event callbacks.


§6.4 Wayfinding / Routing (5 methods)

applyBoost(boost: Boost): Promise<void>

Apply a pre-built Boost object to trigger a deep-link action (entity select or routing). Build boosts with the factory helpers createBoostSelect and createBoostRouting. Throws MAPSTED-1071 on structural validation errors. See Deep-link to a specific map state.


setDefaultRoutingConfig(config: DefaultCustomRoutingConfig): Promise<void>

Override the default wayfinding options (e.g. prefer indoor, include elevators). Accepts a DefaultCustomRoutingConfig object.


calculateDistance(request: CalculationRequest): Promise<CalculationResult>

Request a walking-distance calculation. CalculationRequest requires a start entity ID and a non-empty destinations array. Returns a CalculationResult with per-destination distances. Throws MAPSTED-1012 for missing required fields.


setAccessibilityMode(enabled: boolean): Promise<void>

Toggle accessibility routing: when true, prefers ramps and elevators; excludes escalators and stairs. Throws MAPSTED-1072 if enabled is not a boolean.


clearRoute(): Promise<void>

Clear the currently displayed route and reset the itinerary state (destination set + route options revert to the configured defaults). Programmatic equivalent of the navigation "back" button inside the map iframe. Idempotent: safe to call when no route is active. Throws MAPSTED-1090 when called before the API is READY.


§6.5 Overlays and UI control (8 methods)

setMapOverlayMarkers(markers: MapOverlayMarker[]): Promise<void>

Set (replace) the list of custom map overlay markers. Does not mutate the caller's array. Throws MAPSTED-1080 if markers is not an array. See Use map overlay markers.


centerOnMapOverlay(id: string): Promise<void>

Pan the map to centre on the overlay marker with the given string ID. Throws MAPSTED-1012 for null / empty ID, MAPSTED-1013 for wrong type. See Use map overlay markers.


setFeatureFlags(flags: Partial<FeatureFlagSet>): Promise<void>

Toggle built-in UI widgets. Pass a partial FeatureFlagSet — only specified flags are changed; others retain their current value. Throws MAPSTED-1083 if flags is not a plain object.

Available flags (all boolean):

FlagDefaultControls
showTexttrueEntity name labels on map
showImagestrueEntity image markers
qrCodetrueQR code share button
categoriestrueCategory browser widget
buildingLogotrueBuilding logo in corner
languageSwitchertrueLanguage selector widget
themeSwitchertrueLight/dark theme selector
headerBartrueSearch bar widget
defaultPopuptrueBuilt-in entity popup on click
floorstrueFloor switcher widget
zoomtrueZoom control widget

setLanguage(code: string): Promise<void>

Switch the map UI language. Accepts a BCP 47 tag (e.g. 'en', 'fr-CA'). Throws MAPSTED-1082 for tags that fail BCP 47 validation. See Change the map language.


getLanguage(): Promise<string>

Read the iframe's current language code. Source of truth is the iframe (captures URL ?lang=…, CMS defaults, and in-iframe language-switcher UI changes), so the value stays correct even when setLanguage() was never called from the API. Throws MAPSTED-1090 when called before the API is READY.

See Reading the current language.


showPopup(entityId: MapstedId, options?: { html?: string }): Promise<void>

Programmatically open the default popup for an entity without moving the camera or switching floors. When options.html is provided it is upserted into the entity's iframe data so the popup renders that html. Equivalent to setEntityDataById(id, { html }) + selectEntity(id, { panTo: false, changeFloor: false }) in a single round-trip. Throws MAPSTED-1012 / MAPSTED-1013 for invalid entityId, MAPSTED-1090 before READY. See Programmatically opening a popup.


setTheme(themeOrId: 'dark' | 'light' | string): Promise<Theme>

Apply a map theme by name ('dark' / 'light') or by a custom theme ID returned by getThemes(). Returns the resolved Theme object that was applied. Throws MAPSTED-1090 before READY.


getThemes(): Promise<Theme[]>

Return all themes available for the loaded property (built-in + any property-level custom themes). Each Theme object carries an id, name, and style metadata. Call setTheme(theme.id) to apply one. Throws MAPSTED-1090 before READY.


§6.6 Idle (2 methods)

setIdleTime(ms: number): Promise<void>

Set the idle-detection timeout in milliseconds. Must be a positive finite integer. Throws MAPSTED-1084 on invalid input. See Idle detection and kiosk reset.

resetIdleTimer(): Promise<void>

Programmatically reset the idle-timer countdown without changing the configured idleTime duration. Idempotent when no idle timer is running on the iframe side. Throws MAPSTED-1090 if the API is not yet READY. See Resetting the idle countdown.


§6.7 Sharing (1 method)

getShareUrl(): Promise<string | null>

Build and return a share URL encoding the current map state (property, floor, selected entity). Returns null when no shareUrl base was provided to init(). Use this to power a custom share button outside the iframe UI.

js
const url = await maps.getShareUrl();
if (url) navigator.clipboard.writeText(url);

Throws MAPSTED-1090 if called before READY. See Share URL setup for the full guide.


§6.8 State (2 methods)

getState(): Promise<MapState>

Return a snapshot of the current API state. Key fields:

FieldTypeDescription
sdkStatestringUNINITIALIZED / LOADING / READY / DESTROYED
selectedEntityIdMapstedId | nullCurrently selected entity
zoomLevelnumber | nullCurrent zoom (null until map loaded)
mapCenter[number, number] | nullCurrent centre [lng, lat]
languagestring | nullActive BCP 47 language code
idleState'active' | 'idle'User activity status

subscribe(handler: (state: MapState) => void): Unsubscribe

Register a synchronous handler called on every state change. Returns an Unsubscribe function — call it to stop receiving updates. subscribe() is callable before init() (useful for watching LOADING → READY transitions).


Factory helpers (2 functions)

createBoostSelect(config: string): Boost

Build a Boost that selects an entity by encoded config string. Pass the result to applyBoost().


createBoostRouting(config: string | RoutingConfig): Boost

Build a Boost that triggers a wayfinding route. Accepts either a pre-encoded query string or a RoutingConfig object ({ routing: string; routeOptions?: string }). Pass the result to applyBoost().


Event system (3 functions + constants)

on(event, handler): void / off(event, handler): void / once(event, handler): void

The canonical event API, re-exported from the emitter module. Use these in all new code.

js
// CDN
mapsted.maps.on('select', (entity) => {
  console.log('Selected entity:', entity.entityId);
});

mapsted.maps.once('load', () => {
  console.log('Map fully loaded');
});

// npm
import * as maps from '@mapsted/maps-js-api';
maps.on('floorChange', (floor) => { /* … */ });
maps.off('floorChange', myHandler);

KNOWN_EVENTS

Tuple of the 20 canonical event names. The full list is below; see the events reference for detailed payload shapes.

EventPayload typeDescription
mapMountedvoidiframe mounted and ready
loadvoidMap data fully loaded
selectEntityDataEntity selected by user or code
coordsSelectCoordsDataCoordinates-based entity selected
floorChangeFloorInfoActive floor changed
idleChange{ isUserActive: boolean }Idle / active transition
mapOverlayMarkerSelect{ mapOverlayId, name?, marker?, lat?, lng? }Overlay marker clicked (object payload)
zoomLevelChange{ zoomLevel: number }Zoom level changed
mapCenterChange{ mapCenter: [number, number] }Map centre panned
promotionClickPromotionDataIn-map promotion clicked
navigationStartNavigationDataWayfinding route started
searchText{ searchText: string }Search bar text submitted
detailsViewEntityDataEntity detail panel opened
promotionDetailsPromotionDataPromotion detail panel opened
accessibilityChange{ enabled: boolean }Accessibility mode toggled
themeChangeThemeChangePayload ({ themeId, theme })Map theme changed
boostComplete{ type: 'FLOOR' | 'SELECT' | 'ROUTING' }A deep-link boost finished applying
all{ type: string; … }Fires for every event
protocolErrorProtocolErrorPayloadiframe protocol error
buildingChangeBuildingChangePayload ({ buildingId, previousBuildingId })Active building changed

V2/V3 migration shim (deprecated aliases)

The following names are still exported for backward compatibility but emit a console.warn on first use and will be removed in a future version. Pass strict: true to init() to make them throw MAPSTED-1093 immediately.

Deprecated nameCurrent replacement
initializeinit
setinit (options moved to InitOptions)
changeFloorByIdnavigateToFloorById
changeFloorByNamenavigateToFloorByName
setMapViewsetViewport
centerOnMapoverlaycenterOnMapOverlay
setDefaultCustomRoutingConfigsetDefaultRoutingConfig
changeLanguagesetLanguage
addEventListeneron
removeEventListeneroff
highlightStylepermanently removed (always throws)
setStrictModeinternal — controls shim mode
resetShimStateinternal — called by destroy()

Constants and types

PARENT_ACTION, CHILD_ACTION, FEATURE_FLAG_SETS

Protocol action-type enums and the preset feature-flag bundles ('FULL', etc.). PRIVATE_CHILD_ACTION is intentionally not exported.

Exported types

All public types are re-exported from the API's type module. Key types used throughout this page:

MapstedId · InitOptions · MapInstance · MapState · Unsubscribe · MapEntity · SelectOptions · ViewportOptions · FloorInfo · Boost · RoutingConfig · DefaultCustomRoutingConfig · CalculationRequest · CalculationResult · MapOverlayMarker · CoordsData · FeatureFlagSet · HighlightStyle · ActionTypes

Errors

MapstedError and createMapstedError are exported from ./errors


Current public-API scope

Note: The Mapsted REST entity-catalogue API (GET /v2/properties/:id/entities) is a separate HTTP service — not part of this JavaScript library. The setEntityData() method lets you push data from that REST service into the map renderer, but fetching the catalogue itself requires a direct HTTP call with your API key. See API reference for the REST schema.