TypeScript API Reference
This reference covers @alpenverse/map-view-links. The integration guide shows how to install the versioned package archive and connect a browser viewer. See the shared view specification for the URL format and units.
Core package
Section titled “Core package”Import these functions and types from @alpenverse/map-view-links. They work without a mapping SDK.
Read a link
Section titled “Read a link”readView(carriers: { search?: string; hash?: string }, options?: ViewReadOptions): ReadViewResultparseViewValue(value: string, options?: ViewReadOptions): ParseViewResultUse readView({ search: location.search }) when the application uses the query for view links. Include hash: location.hash if the application also accepts fragment parameters. Omitted carriers default to empty strings. A URL with more than one view parameter yields an invalid result, even when the values match. Use parseViewValue when you already have a decoded value, such as one returned by URLSearchParams.get('view').
| Status | Result |
|---|---|
valid |
view contains the normalized WGS84 state. value retains the decoded payload as supplied. Tagged coordinates can also provide sourcePosition and crsNotices. A valid map can carry a warning when its reference scale is unavailable. |
missing |
Neither supplied carrier contains view. Only readView returns this status. |
invalid |
Use reason as a stable identifier and message as the English explanation. Some errors include a field or both carrier counts. If the reader can propose a validated repair, readView provides replacement search and hash strings and parseViewValue provides a replacement value. |
A repair is a suggestion the caller can present before applying a view. Identical repeated values can be deduplicated, and a heading such as 390h can be wrapped to 30h. Conflicting values require a choice. URL carrier rules
import { parseViewValue, readView } from '@alpenverse/map-view-links';
const result = readView({ search: '?tour=42&view=map:47,8&view=map:47,8' });if (result.status === 'invalid' && result.repair) { console.log(result.repair.search); // ?tour=42&view=map:47,8}
const camera = parseViewValue('cam:47.047,8.474,1800,90h,45t');if (camera.status === 'valid') console.log(camera.view);View and capture types
Section titled “View and capture types”SharedView is a union of MapView and CameraView. Narrow it with view.kind. Both branches use WGS84 latitude and longitude in degrees and heading clockwise from true north.
| Type | Fields and units |
|---|---|
MapView with kind: 'map' |
latitude, longitude, heading, referenceZoom, and optional groundResolution. An unspecified reference zoom is undefined. Ground resolution is WGS84 ellipsoidal metres per CSS pixel along screen-up at the center. |
CameraView with kind: 'camera' |
latitude, longitude, height in metres above mean sea level, heading, tilt from straight down, roll, and diagonalFov in degrees or undefined. Omitted heading, tilt and roll normalize to zero. |
ViewCapture |
A writable map requires kind, latitude and longitude. A writable camera also requires height. Supply at most one map scale, groundResolution or referenceZoom. Other orientation and lens fields are optional. |
Use ground resolution for fresh map shares. The optional z field imports or exports a known reference zoom on the shared 256 CSS-pixel Web Mercator ladder. SDKs may use a different ladder.
The optional camera r field sets roll. A viewer without roll control can restore the supported fields, report that it could not apply the requested roll, and omit roll from fresh captures.
Write or forward a link
Section titled “Write or forward a link”formatViewValue(view: ViewCapture, mapScaleFormat?: MapScaleFormat): string | undefinedcreateViewUrl(base: URL | string, view: ViewCapture | ValidView, options?: ViewCarrier | ViewUrlOptions): URL | undefinedformatViewValue formats a new capture at the shared precision with untagged WGS84 coordinates. By default it uses the scale you supplied. Set mapScaleFormat to 'g' or 'z' to convert a capture with scale to ground resolution or reference zoom when representable. An invalid or unrepresentable capture returns undefined.
createViewUrl takes an absolute base and writes to the query by default. It preserves unrelated parameters and leaves a fragment intact in query mode. Pass 'fragment' to write to an app-owned fragment, or use { ownsFragment: true } in query mode to remove a fragment view. Pass a whole ValidView to forward the original EPSG tag and digits. Pass its view to write a fresh normalized capture.
import { createViewUrl, formatViewValue, parseViewValue, type ViewCapture } from '@alpenverse/map-view-links';
const base = 'https://viewer.example/map?layer=terrain';const capture = { kind: 'map', latitude: 47.047, longitude: 8.474, groundResolution: 7,} satisfies ViewCapture;
const payload = formatViewValue(capture); // map:47.047,8.474,7gconst url = createViewUrl(base, capture);
const incoming = parseViewValue('map:epsg:4326:47.04700,8.47400');const forwarded = incoming.status === 'valid' ? createViewUrl(base, incoming) : undefined;Coordinate reference systems
Section titled “Coordinate reference systems”The reader accepts untagged WGS84 and epsg:4326: out of the box. Enable additional codes in ViewReadOptions.supportedCrs. The core provides webMercatorCrs for EPSG:3857 and swissLv95Crs for EPSG:2056. The Swiss definition uses an approximate transform within the supported LV95 grid and reports an accuracy notice.
import { parseViewValue, swissLv95Crs, webMercatorCrs, type ViewReadOptions } from '@alpenverse/map-view-links';
const options = { supportedCrs: { 2056: swissLv95Crs, 3857: webMercatorCrs } } satisfies ViewReadOptions;const map = parseViewValue('map:epsg:3857:943321.4,5949749', options);A custom CrsDefinition supplies toWgs84(coordinates, epoch?) and heightMetresPerUnit. The transform receives the registered axis order, directions, and units. Configure latitudeAxis for geographic coordinates and supply coordinateEpoch: { year, source } in reader options when the operation requires it. The successful result can include CrsNotice entries for an epoch or a transform approximation. CRS and height rules
Scale, lens and framing helpers
Section titled “Scale, lens and framing helpers”These signatures use MapScale as shorthand for a view with latitude and optional ground resolution, reference zoom and heading. Pass CSS-pixel world sizes and viewport dimensions. Heading is degrees clockwise from true north and defaults to zero when omitted.
| Core function | Behavior |
|---|---|
mapGroundResolution(view: MapScale): number | undefined |
Get ground metres per CSS pixel from either input scale. |
mapReferenceZoom(view: MapScale, heading?: number): number | undefined |
Get shared reference zoom. The optional heading defaults to the view’s heading. |
nativeZoomToReferenceZoom(nativeZoom: number, zoomZeroWorldSize: number): number |
Convert a viewer’s zoom to the shared 256 CSS-pixel ladder. Pass 512 for MapLibre or 256 for Leaflet. |
referenceZoomToNativeZoom(referenceZoom: number, zoomZeroWorldSize: number): number |
Convert shared zoom back to the viewer’s ladder. |
referenceZoomToResolution(referenceZoom: number): number | undefined |
Convert shared zoom to projected EPSG:3857 metres per CSS pixel. |
resolutionToReferenceZoom(resolution: number): number | undefined |
Convert projected EPSG:3857 metres per CSS pixel to shared zoom. |
referenceZoomToGroundResolution(zoom: number, latitude: number, heading?: number): number | undefined |
Convert shared zoom to WGS84 ground resolution at the center. |
groundResolutionToReferenceZoom(resolution: number, latitude: number, heading?: number): number | undefined |
Convert WGS84 ground resolution to shared zoom within the Web Mercator latitude limit. |
convertPerspectiveFov(angle: number, from: PerspectiveFovAxis, to: PerspectiveFovAxis, width: number, height: number): number | undefined |
Convert a full centered perspective angle in degrees. Axes are horizontal, vertical, diagonal and longest. |
topDownCameraForMap(map: MapView, viewport: ViewportDimensions, options?): CameraView | undefined |
Match scale over a local horizontal plane. Options surfaceHeight and minimumDistance default to 0 metres. diagonalFov defaults to defaultDiagonalFov (68.4°). |
mapViewAtCameraFocus(camera: CameraView, viewport: ViewportDimensions, focus?: CameraGroundFocus): MapView |
Estimate flat framing from the viewer’s center-ray hit and eye-to-hit distance in metres. Without a hit, it returns the camera’s horizontal position with no scale. |
import { convertPerspectiveFov, mapReferenceZoom, referenceZoomToNativeZoom,} from '@alpenverse/map-view-links';
const z = mapReferenceZoom({ latitude: 47.047, groundResolution: 7, heading: 25 });const mapLibreZoom = z === undefined ? undefined : referenceZoomToNativeZoom(z, 512);const verticalFov = convertPerspectiveFov(68.4, 'diagonal', 'vertical', 1280, 720);Ground resolution · Lens and viewport
Flat Web Mercator viewers
Section titled “Flat Web Mercator viewers”createWebMercatorViewAdapter(callbacks: WebMercatorAdapterCallbacks, options?: WebMercatorAdapterOptions): ViewLinkAdapterfitFlatMapView(view: SharedView, report: (message: string) => void, limits?: MapZoomLimits): MapView | undefinedlimitMapReferenceZoom(view: MapView, limits: MapZoomLimits): { view: MapView; requestedZoom: number; appliedZoom: number } | undefinedwebMercatorLatitudeProblem(latitude: number): string | undefinedcreateWebMercatorViewAdapter wraps application callbacks for a flat viewer. They exchange WebMercatorViewState with WGS84 center, optional heading and optional native scale. The default native scale is zoom on a 256 CSS-pixel ladder. Pass scale: { zoomZeroWorldSize: 512 } for a 512-pixel ladder or scale: 'resolution' for projected metres per CSS pixel. Leave the native scale as it is when applying a state with omitted scale. Use report to surface adjustments and unsupported views.
fitFlatMapView checks that a link can open in a flat Web Mercator viewer and applies configured reference zoom bounds. limitMapReferenceZoom returns the applied view only when the app’s bounds change the requested zoom. webMercatorLatitudeProblem reports an unsupported latitude using WEB_MERCATOR_MAX_LATITUDE.
import { createWebMercatorViewAdapter, type WebMercatorAdapterCallbacks } from '@alpenverse/map-view-links';
function flatMapAdapter(callbacks: WebMercatorAdapterCallbacks) { return createWebMercatorViewAdapter(callbacks, { scale: 'resolution', maxReferenceZoom: 20, report: console.warn, });}Browser package
Section titled “Browser package”Import these functions and types from @alpenverse/map-view-links/browser. The browser module uses window.location and history.replaceState, keeping unrelated URL parameters and history state.
connectViewLink and watchViewLink
Section titled “connectViewLink and watchViewLink”connectViewLink(adapter: ViewLinkAdapter, options?: ViewLinkOptions): Promise<ViewLinkSession & { initial: ReadViewResult }>watchViewLink(adapter: Pick<ViewLinkAdapter, 'capture' | 'subscribe'>, options?: ViewLinkWatchOptions): ViewLinkSessionconnectViewLink reads the initial link once. It invokes onRead with the result and awaits apply for a valid view before it samples the restored capture. Use watchViewLink when your app restores the view itself. It uses restoredCapture when supplied and otherwise takes a capture when it attaches. A matching capture keeps the incoming payload unless the app selects a different map scale format.
When neither a startup capture nor a supplied baseline is available, the first available capture may replace the incoming URL. To preserve a rejected link while the user reviews it, wait for a capture before starting synchronization.
| Callback | Contract |
|---|---|
apply(view: SharedView, link: ValidView) |
Restore the view. Return void or Promise<void> when the restored capture is ready. |
capture() |
Return the live ViewCapture or undefined while the viewer cannot supply one. |
subscribe(update) |
Call update when a capture becomes available or the viewer changes. Return an unsubscribe function. |
| Option | Default and behavior |
|---|---|
carrier |
'query' by default. Choose 'fragment' to read both carriers and write to the app-owned fragment. |
ownsFragment |
false. Set it to true in query mode to read both carriers and remove fragment view parameters when writing to the query. |
restoredCapture |
Optional on watchViewLink. Supply the view actually applied by the adapter, including any snapping or clamping. |
interval |
100 ms between scheduled address-bar writes. |
mapScaleFormat |
'g' for fresh shares. Select 'z' to write reference zoom. |
onUnsupportedScale |
Optional callback when a fresh map share falls back to a place with no scale. |
readOptions, onRead |
Optional settings on connectViewLink for CRS support and initial read results. |
import type { ViewCapture } from '@alpenverse/map-view-links';import { watchViewLink, type ViewLinkAdapter } from '@alpenverse/map-view-links/browser';
function syncAfterRestore( adapter: Pick<ViewLinkAdapter, 'capture' | 'subscribe'>, restoredCapture?: ViewCapture,) { return watchViewLink(adapter, { restoredCapture, onUnsupportedScale: console.warn });}In dual-carrier mode, connectViewLink reports conflicting-carriers when both the query and the fragment contain a view. When the viewer stays unchanged, the URL keeps the supplied payload and carrier. A fresh write keeps only one view and preserves unrelated fragment content, query parameters and history state.
Browser integration example with connectViewLink
ViewLinkSession
Section titled “ViewLinkSession”| Method | Behavior |
|---|---|
getUrl(): URL |
Flush pending view changes and return the synced URL. |
getCurrentViewUrl(options?): URL |
Capture a fresh share. This can update the address bar. Return the current URL if no share can be formatted. Pass { onUnsupportedScale: false } to suppress the scale notice for that call. |
getCurrentView(): ViewCapture | undefined |
Read the live capture without writing the URL. |
setMapScaleFormat(format, options?): void |
Set 'g' or 'z' for future writes. Pass { preserveIncoming: true } when setting the initial format and keeping a supplied payload until navigation. |
dispose(): void |
Unsubscribe and cancel pending writes. Call on viewer teardown. |