CTWeb Maps SDK v1
getDataCoverage() returns a defensive copy of the active archive coverage and resolution tiers, or undefined with an older API. getViewBounds() returns visible southwest/northeast coordinates. fitDenmark({padding?:number,duration?:number}) frames Denmark including Bornholm (defaults 24px/0ms). See coverage and integration guidance.
The framework independent SDK uses MapLibre GL JS, PMTiles and DOMPurify. Load the stylesheet and give each container an explicit height. Each map has independent data, controls, filters, popup, event handlers, private request protocols and teardown.
<link rel="stylesheet" href="https://maps.example/sdk/v1/maps.css">
<div id="map" style="height: 500px"></div>
<script type="module">
import { Map } from 'https://maps.example/sdk/v1/maps.mjs';
const map = new Map({
container: 'map',
baseUrl: 'https://maps.example/',
// This host backend keeps the project secret. Never put it in browser code.
tokenProvider: async signal => {
const response = await fetch('/your-backend/map-token', { signal });
if (!response.ok) throw new Error('Token unavailable');
return response.json(); // { accessToken, expiresAt: ISO string or epoch milliseconds }
},
map: { accessibleList: true },
markers: [{ id: 'example', coordinates: [12.5683, 55.6761], title: 'Synthetic example', popup: { text: 'Example content' } }],
});
await map.ready;
// Call map.destroy() when unmounting a component.
</script>
For script tags, load /sdk/v1/maps.js and instantiate new CTWeb.Maps.Map(options). ESM exports version; script tags expose CTWeb.Maps.version. Both identify the concrete distribution version injected at build time. The major alias /sdk/v1/ selects the current compatible distribution; pin /sdk/{version}/maps.mjs or maps.js plus its stylesheet for a specific release. Type declarations are generated from sdk/tsconfig.json; all public input, event and configuration types are exported by sdk/index.ts.
Connection and resource policy
container is an element or element ID. baseUrl is the SDK server origin. tokenProvider(signal) may return a token string or { accessToken, expiresAt }, synchronously or asynchronously. Structured tokens are renewed before expiry using a buffer of 10% of their accepted remaining lifetime, capped at 30 seconds. This keeps valid short-lived tokens cached rather than issuing a new one for every resource. A string token invokes the provider for each request. Concurrent renewals share one provider promise. One cancelled tile does not cancel renewal for other tiles. The provider receives the map lifetime signal and should honor it.
The SDK fetches GET /api/v1/map-config with Bearer authorization. Its response is { dataVersion, dataUrl, styleUrls: { standard, nature, dark }, availableThemes?, sessionExpiresAt?, maximumSessionSeconds?, defaults?, clientId? }. availableThemes optionally restricts the project to a nonempty subset of supported themes; disabled initial or requested themes reject. getAvailableThemes() exposes the authorized set after readiness. The data URL is immutable within each advertised data session; ordinary style changes retain it. getDataVersion() and getDataUrl() expose the current session's version after readiness.
When sessionExpiresAt is supplied, the SDK renews map configuration shortly before that UTC deadline, with a lead time of 10% of the remaining session or 30 seconds, whichever is smaller. A reported maximumSessionSeconds additionally caps the accepted lifetime from receipt. refreshSession() also renews explicitly. A new archive URL is authenticated and its PMTiles header validated before the map switches. A successful switch reapplies the current authorized theme while preserving camera, marker/filter state, shapes and the open popup; obsolete archive caches are released. A changed data version must use a changed immutable URL. The server may revoke a theme; renewal then selects its first authorized theme.
Failed configuration or new-archive preflight leaves the previous configuration/map active. Automatic renewal makes at most five failed attempts, with delays of 1, 2, 4 and 8 seconds, and emits sessionerror / sessionexpired so a host can explain the issue and offer manual retry. A cached old map cannot guarantee new tile availability after server retention ends during a prolonged outage. Successful renewal resets the retry counter. destroy() cancels the timer and pending authenticated work. Explicit fixtures without a session expiry schedule no renewal. No session state is stored in browser persistence.
For isolated tests, serverConfig supplies that response directly. styles optionally supplies inline MapLibre v8 styles by theme; a normal production instance should use server styles. A protomaps vector source or any PMTiles source in each style is rebound to the pinned archive. Other sources remain subject to the same URL policy.
Every uncached PMTiles byte Range obtains current authorization through AuthorizedSource. The source validates HTTP 206, Content-Range, response length and stable ETag. Protected style, glyph, sprite and other renderer requests run through a per-instance asynchronous protocol installed by transformRequest, allowing token renewal and a single 401 retry. Requests omit credentials and reject redirects. The public worker is sdk/{version}/worker.mjs relative to the SDK base URL, using the bundle's concrete exported version even when loaded through /sdk/v1/. This prevents a pinned older SDK from selecting a newer image's unversioned worker. Concrete bundle archives must retain their matching worker across server upgrades. Unbundled test-source execution falls back to v1. Host CSP must permit the worker service origin and MapLibre's required blob worker handling.
Default permitted resource origins are the SDK server and hosting website. allowedOrigins: ['https://icons.example'] adds exact HTTP(S) origins; paths, wildcards, credentials, data URLs, JavaScript URLs and other schemes are rejected. Only SDK-origin resources receive the Bearer token. The SDK performs browser fetches and provides no server-side URL fetching endpoint. SVG icon data is sanitized before decoding; remote icon files must have PNG or SVG MIME types, be at most 2 MiB and decode to at most 2048 × 2048 pixels. Loading failure emits iconerror and uses the default pin. Blob/data URLs are used only internally for trusted generated image decoding.
Explicit trusted DOM factories and { trustedDOM: element } bypass content sanitization by design. Their author is responsible for DOM security, resource policy, privacy and accessible content. Arbitrary host page DOM and independently imported scripts are outside the SDK request boundary.
Configuration
Configuration recursively merges in this order: built-in defaults → platform → server/project defaults → explicit project → map → component. undefined inherits; arrays replace; false and 0 remain effective. Prototype keys are rejected at every object/array depth. Inputs are validated before renderer use. Use await updateConfiguration(patch) or its setOptions(patch) alias for live changes instead of mutating config. The patch merges into current settings, validates before application and updates controls, ranges, marker defaults and clustering without replacing the renderer or clearing data/filter state. Camera center/zoom are preserved unless supplied, with zoom clamped to new configured ranges and MapLibre viewport/geographic constraints.
Explicit null clears maxBounds and optional clustering.icon, clustering.html, clustering.categoryColors and clustering.radiusExpression. This supports switching designs without retaining a previous factory/icon. Other required settings reject null. For example, await map.setOptions({ clustering: { icon: null, html: null, categoryColors: null, enabled: true } }) restores the standard cluster design.
| Setting | Default / behavior |
|---|---|
center, zoom, minZoom, maxZoom |
[10.4, 56.1], 7, 0, 19; coordinate order is longitude, latitude |
maxBounds |
Unset; optional [southwest, northeast] coordinate pairs constrain navigation; endpoints must increase longitude/latitude; null removes the constraint |
theme, language |
standard, da; supported themes standard, nature, dark; Danish label policy comes from the supplied local style |
rotation, compass |
false, false; rotation gestures and keyboard rotation disabled by default |
fullscreen, geolocation |
true, false; geolocation control never requests location during initialization |
accessibleList |
false; creates a sibling section containing keyboard-operable buttons for visible markers |
maxHTMLMarkers |
100; hard validated maximum 1000; GPU markers should be used for large collections |
markerDefaults |
{ width:32, height:40, color:'#1976d2', anchor:'bottom', rotation:0, offset:[0,0], opacity:1, zIndex:0 }; optional allowed icon URL or built-in categoryIcon, both clear with null |
popupDefaults |
{ minWidth:120, maxWidth:300, offset:12, closeButton:true, closeOnClick:true }; optional anchor, className, onOpen(marker), onClose() |
clustering |
See below |
branding |
{ visible:true, text:'CTWeb Maps', position:'bottom-left' }; four MapLibre corner positions supported |
scrollZoom |
'enabled' (default), 'disabled', or 'ctrl'; controls wheel and trackpad scroll zoom |
OpenStreetMap/Protomaps attribution is always installed independently of branding and has no ordinary configuration disable option. renderer is limited to MapLibre canvasContextAttributes, renderWorldCopies, fadeDuration and maxTileCacheSize.
Scrollzoom og branding
Brug de offentlige indstillinger i integrationer som YourTicket; adgang til SDK'ets private renderer er ikke nødvendig:
const map = new Map({
container: 'map',
baseUrl: 'https://maps.example/',
map: { scrollZoom: 'ctrl', branding: { visible: false } },
});
await map.ready;
await map.setOptions({ scrollZoom: 'disabled' });
await map.updateConfiguration({ scrollZoom: 'enabled', branding: { visible: true } });
enabled lader musehjul og trackpad zoome kortet. disabled lader siden scrolle uden at zoome kortet. ctrl kræver Ctrl eller ⌘ Cmd på scrollhændelsen og viser ellers den danske hjælpetekst “Hold Ctrl eller ⌘ Cmd nede, mens du scroller, for at zoome på kortet.” Teksten annonceres via en høflig live-status, blokerer ikke interaktion og forsvinder automatisk. Fokustab, vinduets blur og skift af synlighed nulstiller den midlertidige aktivering. Zoomknapper, tastaturzoom og touch-pinch bevares i alle tilstande.
Udelades scrollZoom, bevares standardadfærden (enabled), medmindre et tidligere konfigurationslag har angivet en anden tilstand. Runtime-patches bruger felterne direkte, uden en ekstra map-indpakning. Ugyldige værdier afvises før ændringen anvendes. destroy() fjerner lyttere, hjælpetekst og dens timer.
branding: { visible: false } skjuler CTWeb Maps-branding både ved oprettelse og under drift. Standardværdien er true. Kortkildernes OpenStreetMap/Protomaps-attribution bevares.
Marker lifecycle
setMarkers(array) atomically replaces all marker records; duplicate IDs or invalid entries reject the entire replacement. addMarker, addMarkers, updateMarker(id, patch), removeMarker, clearMarkers, getMarker and getMarkers provide individual lifecycle operations. data is retained as application metadata and never serialized into GPU source properties or fetched by the SDK. Marker IDs are nonempty strings of at most 200 characters. Coordinates must be finite longitude −180..180 and latitude −90..90.
Each marker supports:
| Option | Meaning |
|---|---|
id, coordinates |
Required stable identifier and [longitude, latitude] |
data, title, description, tooltip |
Arbitrary caller metadata, accessible label/list text, escaped default-popup description and escaped hover text |
categories, groups |
String arrays for visibility filters; hiding any membership hides that marker |
visible |
false hides one marker |
icon |
Allowed PNG/SVG URL; cached per instance; takes precedence over generated category/color pin |
iconSvg |
Inline SVG string, sanitized and rasterized as a cached GPU icon; takes render priority over icon. Same 2 MiB / 2048-pixel bounds and iconerror/default-pin fallback; no URL-policy bypass. Individual markers only. |
width, height, anchor |
1..256 pixels, default 32 × 40, bottom/center/top anchor |
color, categoryIcon |
Generated pin color; built-in nature, food, parking, home, information pictograms |
rotation, offset, opacity, zIndex |
Finite degrees, [x,y] pixel offset, 0..1 opacity, finite symbol/DOM ordering |
clusterGroup |
Independent cluster partition; omitted means default; different values never cluster together |
html(marker) |
Explicit trusted DOM factory for bounded HTML markers; joins clustering and appears only when unclustered |
popup, popupOptions, onClick |
Content/provider, overrides for popup defaults and a per-marker click hook returning false to suppress default action |
Default icon URLs and category icons participate in the same platform/project/map/component hierarchy as marker dimensions/color. Missing or undefined individual settings inherit; an individual URL overrides the default URL, while an explicit individual category icon selects that built-in pin instead of an inherited URL. A default custom URL takes precedence when both default URL/category are configured. All URL defaults use the same allowlist/cache/fallback policy as individual URLs. Clear a prior optional default with markerDefaults: { icon: null } or { categoryIcon: null }.
setMarkersVisible(boolean), setGroupVisible(group, boolean), setCategoryVisible(category, boolean) and setFilter(predicate?) recompute visible source data, cluster counts and list content. Filters operate on full marker metadata. Data updates are asynchronous to the renderer; markerschange signals source submission. Actual GPU tile processing completes afterward. Camera movements preserve all filtering state. Factories and predicates should be deterministic and fast.
Clusters and coincident points
For externally clustered data, use ordinary markers with clustering: { enabled:false, spiderfy:false }. The SDK does not need to cluster those points again. See the complete YourTicket integration for .NET Framework 4.8 / Classic ASP anonymous token brokering, inline SVG, multi-place popups, backend cluster zoom translation and teardown.
clustering supports enabled:true, radius:50, minPoints:2, maxZoom:16, color:'#1976d2', textColor:'#fff', showCount:true, maxHTML:100, spiderfy:true. Default blue cluster radii grow at counts 10, 100 and 1000. radiusExpression supplies a MapLibre expression. categoryColors maps the first marker category to a dominant-category cluster color, with configured order resolving ties. icon supplies an optional GPU cluster icon and keeps the count label. html(count, clusterId, cluster?) overlays bounded trusted HTML cluster elements. GPU circles remain as fallback, including beyond the HTML cap.
clusterclick includes { id, count, coordinates, group }. getClusterLeaves(id, limit=100, offset=0, group='default') returns original marker records; maximum page size is 10000. expandCluster(cluster) zooms to the cluster expansion zoom. openClusterPopup(id, content?, group='default') shows an escaped list of up to 100 marker names, or supplied content. Cluster IDs are transient and scoped to their partition; obtain fresh IDs after data/filter changes.
Exact coordinate coincidences spiderfy on cluster activation, or on an unclustered marker click above clustering zoom. Spread markers expose keyboard-operable buttons and original popup callbacks. At most 100 are spread simultaneously; full membership remains available through paged leaves and the accessible list. Spiderfy currently uses a numbered spiral without connecting legs and closes on camera movement/data changes.
Popups and events
openPopup(id, content?) accepts a plain string, { text }, { html }, { trustedDOM: element }, or a marker's async provider (marker, signal) => content. Without custom popup content, defined marker title and description produce an escaped heading and paragraph. Strings use textContent. HTML uses maintained DOMPurify sanitization, disallows forms/embedded active content/styles, and checks remaining URL attributes against the resource policy; images with prohibited sources are removed entirely. Explicit trusted DOM bypasses sanitization. Providers show a Danish loading state and a generic error state; errors are emitted separately. Opening another popup, changing marker data/filter visibility or destroying the map aborts prior work and prevents stale content replacing newer content. Providers must honor the signal for their own expensive operations.
Popups focus the dialog during loading and after content arrives, close on Escape, and restore previous focus on close. popupOptions overrides min/max width, anchor, offset, closeButton, closeOnClick, custom className and onOpen(marker) / onClose() callbacks. Both close flags default true; disabling the button still permits Escape, including during loading. closeOnClick:false keeps the popup open when clicking the map. A custom class list is at most 200 characters, uses ASCII names beginning with a letter/underscore, and separates names with single spaces; an empty string clears custom classes. The internal ctweb-popup namespace remains. Only one popup is open per map; explicitly opening another still replaces the current one. closePopup() closes explicitly. Constructor onMarkerClick(marker, event) / onClusterClick(cluster, event) hooks run before marker onClick / clustering.onClick; returning false suppresses subsequent hooks/default action, while emitted click events still fire. Cluster HTML factories receive full partition metadata as their third argument. Optional clustering.onClick clears with null. openPopup and openClusterPopup also accept async marker-style providers as explicit content arguments, enabling a cluster hook to load custom popup data with cancellation and return false to suppress zooming.
Popup dimensions are capped to the actual map container, with an internal scroll viewport for oversized content and responsive image widths. Provider completion, image loading, content/container resizing and map movement refresh layout using public Popup methods; a screen translation keeps the box inside the map while reserving bottom attribution/branding space. This may shift the visual tip for a popup too large to fit beside its geographic anchor. The close button remains outside the scroll viewport and above navigation controls. Layout refresh does not steal focus or move the camera. Closing/destroying disconnects popup observers/listeners and cancels pending layout frames.
Subscribe with on(type, handler) and unsubscribe with off(type, handler). Events include ready, error, click, moveend, markerschange, markerclick, clusterclick, stylechange, configurationchange, sessionrefresh, sessionerror, sessionexpired, spiderfy, iconerror, popupopen, popuploading, popupload, popuperror, popupclick, popupclose, destroy. Each event has type and relevant marker, cluster, error, coordinates, data versions, attempt count or theme/count fields. The ready promise rejects on initial renderer/resource failure; attach error handlers and catch it.
popupclick delegates clicks from popup content, including nested trusted-DOM buttons and links, and supplies the marker plus the original DOM Event. It fires once in capture phase, so a content handler that immediately closes the popup still produces the notification. The separate close button produces popupclose, not a content click. Closing/replacing/destroying aborts the delegate. This is a local browser notification and performs no upload.
map.on('popupclick', event => {
console.log(event.marker.id, event.originalEvent.target);
});
Geometry, camera, controls and teardown
addGeoJSON(id, geometryOrFeatureOrCollection, options), addLine(id, coordinates, options), addPolygon(id, rings, options), addCircle(id, center, radiusMeters, options), and removeShape(id) manage GPU vector overlays, including recursive GeometryCollections. Circles are geographic 64-segment polygons. Lines require at least two finite positions; polygon rings are closed with at least four positions. Options: color, width (0..100), opacity (0..1), fillColor, fillOpacity (0..1). Shape IDs permit 1..100 letters, digits, underscores or hyphens. Reusing an ID updates its data and styling. Geometry fitting currently uses longitude/latitude bounds and does not choose a shortest antimeridian span; maxBounds likewise requires a non-wrapping west-to-east rectangle.
flyTo(center, zoom?), setCenter, setZoom, getCenter, getZoom, fitGeometry(data, padding=40), fitMarkers(padding=40) and resize() control the view. fitMarkers fits visible markers and is a no-op on an empty set. setTheme(theme) asynchronously changes style and restores markers, source partitions, icons, shapes, controls, filters and camera. ResizeObserver updates rendering when container dimensions change.
The fullscreen control uses the browser Fullscreen API where supported. With geolocation:true, users can click the geolocation control; locate(event) is also available from a trusted active click/key gesture. Browser permissions/HTTPS requirements still apply.
destroy() is idempotent. It aborts SDK requests and providers, invalidates pending style/data work, removes DOM markers/popups/list/observer, removes renderer controls/listeners/canvas, releases image bitmaps, clears PMTiles caches and unregisters only that instance's private protocols. Destroying one instance leaves others active. Methods requiring the renderer must run after ready. External host resources created by trusted content factories remain the host application's cleanup responsibility.
Verification
Run npx tsc -p sdk/tsconfig.json, npx tsc -p tests/sdk/fixtures/tsconfig.json, node --test tests/sdk/*.test.mjs and, with the development preview running, npx playwright test -c tests/sdk/playwright.config.ts. The consumer fixture checks ESM and ambient global declarations under strict NodeNext resolution without skipping library checks. Unit tests exercise deep merging/prototype defenses, coordinate/geometry/bounds validation, URL policy, cancellation-safe token coalescing, token renewal/retry, cookie/redirect settings and PMTiles range/identity checks. SDK Chromium tests cover clustering, icons, popup cancellation, project theme policy, runtime controls, bounds, GeometryCollections, timed immutable-data renewal, failed-renewal continuity and cleanup. Performance/accessibility evidence is in docs/performance.md and docs/browser-accessibility-results.md. These tests do not establish universal browser compatibility or accessibility compliance by themselves.
The complete generated signatures, parameter types and defaults are available in API reference. Renderer source/layer identifiers beginning with ctweb- are reserved for SDK overlays; use different identifiers in custom basemap styles.