# Show a map

> Canonical URL: https://docs.mountaya.com/en/sdks/swift/map/
> Last updated: 2026-11-27
> Rules for agents: https://docs.mountaya.com/llms.txt#rules-for-agents

Draw a Mountaya map in SwiftUI with MapEngine and MapView: itineraries, the camera, taps, refusals, the readout, the watermark and waypoints.

A map is a `MapEngine` that holds what the map shows, and a SwiftUI `MapView` that draws it on iPhone and iPad. Turn on the `Elements` trait first ([install](https://docs.mountaya.com/en/sdks/swift/install.md#platform-setup)).

## Render the map

```swift
import MountayaClient
import MountayaElements
import SwiftUI

struct TrailMap: View {
  @State private var map: MapEngine

  init(mountaya: Mountaya) {
    _map = State(initialValue: MapEngine(client: mountaya))
  }

  var body: some View {
    MapView(map)
      .ignoresSafeArea()
      .task { try? await map.setTerrain() }
  }
}
```

The map fetches its style and tiles with your client's key. `setTerrain()` shows the first terrain of your catalogue.

- `MapEngine(client:style:terrainVariant:camera:labelLanguage:paint:glyphs:geolocation:transformRequest:)` is `@MainActor` and `@Observable`: a view reading `map.state` is drawn again when it changes. It builds on every platform; only `MapView` needs iOS with the `Elements` trait.
- `MapView(_:readout:onReady:onTap:onCameraChange:)`. `onReady` hands MapLibre's own `MLNMapView` once the first style loads, for anything the view does not wrap; an app that uses it imports MapLibre within the package's range.
- `setTerrain(_:)` shows a terrain by slug, the catalogue's first by default; `setTerrainVariant(.dark)` asks for the dark variant; `setStyle(_:)` shows a style of your own. Everything drawn is drawn again on a new base map, and one that fails to arrive leaves the one shown.
- Labels speak the language you give the engine (`labelLanguage:` or `setLabelLanguage(_:)`), else your client's `language`, else the device's.
- Every request MapLibre makes for the map carries the client's credential, language and `X-Mountaya-Client` to the Tile API, and nothing to any other host. `transformRequest:` is your hook over those requests, called first. MapLibre's request hook is process-wide: two maps on one Tile API under different credentials send the credential of the map shown last.
- `close()` ends the engine: a command afterwards does nothing, and one that answers something (`loadLayers()`, `locate()`) throws `MapError` of kind `.closed`.

## Draw an itinerary

```swift
import MountayaElements
import MountayaGeo

@MainActor
func showTour(on map: MapEngine) async throws {
  try await map.setItinerary(
    "0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21", fit: CameraFit(padding: PixelPadding(48)))
  try await map.setZones(true)
}
```

A later call replaces the itinerary drawn. Cancelling the task withdraws a call still loading.

- Each call draws in a slot of its own: `setItinerary(_:fit:)`, `setItineraries(_:)` (your scope's published itineraries), `setCollection(_:fit:)`, `setZones(_:)`, and `setSpecification(_:named:)` for a style specification you hold under a name. The latest call for a slot draws; one that answers after a later call answers `false`. `clearItinerary()`, `clearCollection()` and `clearSpecifications()` empty them.
- `setZones(_:)` takes a `Bool`, positionally, where the Dart SDK names it `shown:`. Map commands are synchronous where they change only state (`setInstant(_:)`), as in Kotlin; Dart awaits them.
- An itinerary's restricted stretches are striped beside its line until `setAccessRestrictionsVisibility(false)`.
- `addSource(_:)` and `addLayer(_:)` draw content of your own at a `LayerRank`. `editLayer(_:paint:layout:)` merges a patch: a member set to a value replaces the one held; a member written `nil` is unstated and keeps the value held; `JSONValue.null` sets the property to `null`, which sends it back to the style's default. So `["line-width": nil]` keeps the width, and `["line-width": .null]` clears it.
- Data API results draw under ids of their own: `addDirections`, `addIsochrones`, `addMatrix`, `addPlaces`, `addSuggestions`, `setPointsOfInterest`, each with its `edit…` and `removeAnalysis(_:)`. Three geometry slots (`GeometrySlot`) draw over everything: `setGeometry(_:in:color:)`, `clearGeometry(in:)`.
- `addMarker(MapMarker(id:position:glyph:label:))` draws a pin above everything; `editMarker(_:position:color:glyph:label:)` keeps each member left `nil`. A marker is a pin: it brings no view of its own, and its tap reaches `MapView`'s `onTap` with its id.

## Move the camera

```swift
import MountayaElements
import MountayaGeo

@MainActor
func frameChamonix(on map: MapEngine) throws {
  try map.ease(to: CameraTarget(center: [6.8712, 45.9231], zoom: 12))
  // Chamonix to Argentière: west, south, east, north.
  try map.fitBounds([6.80, 45.85, 7.00, 46.00], with: CameraFit(padding: PixelPadding(48)))
  map.resetNorth()
}
```

- `jump(to:)`, `ease(to:)` and `fly(to:)` move to the members a `CameraTarget` states and keep the rest. `fitBounds(_:with:)` frames `[west, south, east, north]`, computed on the map's canvas, facing north, under `CameraFit.maxZoom`.
- `zoomIn()`, `zoomOut()` and `resetNorth()` are the controls' moves. `setMaxBounds(_:)` holds the camera to a box (nil lifts it; once lifted, the view stays within the world's edges, the antimeridian a wall). `setZoomBounds(min:max:)` holds a zoom range; a limit left out is kept and `.released` goes back to MapLibre's own, 0 and 25.5.
- `locate()` frames the device's position at zoom 16 at most and answers it. It never asks for location access: a fix your app holds no permission for, or an approximate one, throws `MapError` of kind `.fixRefused(.denied)`; `.noApi` and `.unavailable` are the other `GeolocationRefusal`s. Asking is your app's flow ([navigation](https://docs.mountaya.com/en/sdks/swift/navigation.md#location)).
- A command handed something a map cannot take throws `MapError` (its `kind`: `layerNotFound`, `markerNotFound`, `positionRefused`, `numberRefused`, `maxBoundsRefused`, `zoomBoundsRefused`, `terrainNotFound`, `overlayNotFound`, `analysisNotFound`, `kindMismatch`, `typeRefused`, `noInput`, `fixRefused`, `closed`) and leaves the map as it was.

## Respond to the user

`MapView` hands you each tap and each camera at rest:

```swift
import MountayaElements
import MountayaGeo
import SwiftUI

struct TappableMap: View {
  let map: MapEngine
  @State private var picked: String?
  @State private var zoom = 0.0

  var body: some View {
    MapView(
      map,
      onTap: { tap in picked = tap.marker },
      onCameraChange: { camera in zoom = camera.zoom }
    )
    .overlay(alignment: .bottom) { Text(picked ?? "Zoom \(Int(zoom))") }
  }
}
```

For what lands under a tap, read the map's events:

```swift
import MountayaElements

@MainActor
func listen(to map: MapEngine) async {
  for await event in map.events() {
    if case .featureTap(_, let features) = event {
      print(features.map(\.layer))
    }
  }
}
```

- `MapTap` carries `position` (`[longitude, latitude]`), `point` (on screen) and `marker` (the id of the marker it fell on, if any).
- `events()` is an `AsyncStream<MapEvent>`: `.tap(MapTap)`, `.longTap(MapTap)`, `.featureTap(position:features:)`, `.featureHover(position:features:)` (a pointer on iPad), `.accessRefused(status:url:)`, `.accessRestored`, `.failure(url:status:cause:)`, `.layersChange(TileSchema.Layers?)`. Swift and Dart say tap; Kotlin says click.
- Point queries answer what the map drew under a point, topmost first, never its base map: `features(at:)`, `pois(at:)`, `zones(at:)`, `itineraries(at:)`, each a `QueriedFeature` with its `layer`. `elevation(at:)` asks the Data API.

## Hear what the map refuses

A request the map's own loader cannot complete reaches its events. Listen for them and log each:

```swift
import MountayaElements

@MainActor
func logRefusals(of map: MapEngine) async {
  for await event in map.events() {
    switch event {
    case .accessRefused(let status, let url):
      print("refused \(status): \(url)")
    case .failure(let url, let status, let cause):
      print("failed \(status.map(String.init) ?? "with no answer"): \(url)", cause ?? "")
    default:
      break
    }
  }
}
```

While a refusal stands, `map.state.isAccessRequired` is true: show your own notice over the map.

- A `401`, `402` or `403` on one of the map's own requests is told as `.accessRefused(status:url:)` and stands in `state.isAccessRequired` until the source it came from loads again (`.accessRestored`). A refusal on the base map's tiles names no source and stands until the next style loads.
- A request that failed with no answer is `.failure(url:status:cause:)`; `cause` is what reading the client's credential threw where the request never left for want of one. A failed tile is repeated on MapLibre's own schedule.
- A tile asked for before the first session token lands goes out under the key alone.

## Read a point

A long press opens a readout of the point: the terrain's altitude, slope and aspect, what is drawn there, and the coordinates. Turn it off with `MapView(map, readout: false)`; the long press still reaches `events()`.

- The readout opens at a long press (or a right click), 288 points wide, its top-left corner at the point, flipped to stay inside the safe area and clear of the watermark's frame. It shows the point of interest and the zone drawn there, the classic overlay's band, the terrain read off the elevation tiles through the client's tile transport and decoded off the main thread, the moment the map shows in the device's time zone, and the coordinates, latitude first, to five places, with a copy button. A tap or a camera move closes it and cancels the tile reads still out.
- The same terrain read is Geo's: `elevationTilesAt(_:source:)` and `terrainFromElevationTiles(_:source:tiles:)` ([geo](https://docs.mountaya.com/en/sdks/swift/geo.md#terrain)).

## Attribution and watermark

The map shows the Mountaya watermark in the top-left corner of its safe area, unless your organization holds white label. Keep your own views clear of it:

```swift
import MountayaGeo

// Where a bar of yours across the top starts, as the map's read of your organization stands.
func barTop(safeAreaTop top: Double, read: OrganizationRead) -> Double {
  isWatermarkKeptClear(read) ? top + watermarkClearance + 8 : top
}
```

The credit button lists the map's sources, Mountaya first.

- The map reads your organization once per publishable key and Map Studio API origin, shared by every map of the process (`loadOrganization()`, through `postOrganizationLookup`). It decides the watermark and nothing else. `map.organizationRead` is `.waiting`, `.answered(whiteLabel:)`, `.failed`, `.timedOut` or `.noKey`; a client holding a share token reads nothing and `loadOrganization()` answers nil.
- The frame: `watermarkWidth` 180 points, `watermarkHeight` about 76, `watermarkInset` -4 from the safe area's top-left corner, `watermarkClearance` how far below the safe area's top it ends. `isWatermarkKeptClear(_:)` is true from the first drawing until the read answers white label. Nothing draws while the first read waits, for one attempt's budget at most (35 seconds), then the mark.
- The safe area is the inset the system reports, never one your layout sets, so a full-bleed map shows the mark below the status bar. The SDK's controls, panels, readout and marker labels keep clear of the frame. A press opens Mountaya's site in the device's browser; nothing you state hides it. A snapshot through `onReady` records MapLibre's canvas without it.
- `map.credits` lists what the map credits, Mountaya first, which its credit button shows.

## Place waypoints

Begin an edit, and each tap places the waypoint. A tap near the itinerary's line snaps onto it:

```swift
import MountayaElements

@MainActor
func moveWaypoint(on map: MapEngine, along line: [[Double]]) async throws {
  try await map.setItinerary("0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21")
  map.setActiveSegments([line])
  try map.beginWaypointEdit("5f2b8c1e-7a4d-4e9b-b3c6-0d8e1f2a4b67")
}

// Once the reader has tapped where it goes: where the waypoint now stands.
@MainActor
func finishEdit(on map: MapEngine) -> [Double]? {
  map.endWaypointEdit()?.position
}
```

- `MapView` places the waypoint at each tap during an edit. A tap within 40 points of an active segment (`setActiveSegments(_:)`) places it on the line, `isSnapped` true. A map drawn some other way calls `placeWaypoint(at:through:)` with its own `ScreenProjection`.
- `state.waypointEdit` holds the edit in progress (`waypointId`, `position`, `isSnapped`); `endWaypointEdit()` answers it and ends the edit.
- Saving the waypoint is your write: `mountaya.studio.itineraries.patchItineraryWaypoint(itinerary_id:waypoint_id:body:)` under a member's session.

## Next steps

- [Controls and panels](https://docs.mountaya.com/en/sdks/swift/controls.md): Zoom, layers, points of interest, units and time.
- [Search](https://docs.mountaya.com/en/sdks/swift/search.md): A search box over places, itineraries and zones.
