Skip to main content
Version: 1.x

Using the map in SwiftUI

Embed a Wemap map in a SwiftUI view, and bind its state to yours.

Overview​

Map is a SwiftUI view over the same MapView the UIKit API exposes. Everything imperative — navigation, points of interest, itineraries — is reached through the map view handed to onLoaded, while the state you want to render is delivered through bindings.

import SwiftUI
import WemapMapSDK

struct MapScreen: View {

let session: MapSession

@State private var map: MapView?
@State private var position: MapCameraPosition = .automatic

var body: some View {
VStack {
Map(session: session)
.onLoaded { map = $0 }
.onFailed { print("Failed to load the map: \($0)") }
.cameraPosition($position)

Button("Locate me") {
withAnimation { position = .followUser(bearing: .heading) }
}
}
}
}

Own the session above the view​

A MapSession loads a map's data once and is shared by the Wemap views and location sources of a screen — that sharing is what keeps navigation, point-of-interest selection and the user location consistent between them. So create it in app state, a router, or a view model, and pass it down. A session created inside a view dies with the view and refetches its data over the network on every navigation.

Important

One session serves one Map and one GeoAR — that pairing is what it is for. Two maps on one session is not supported: they contend for a single renderer slot, the newer one wins, and the older stops receiving selection, itinerary and navigation updates while still drawing. Give the second map its own session. The SDK logs an error naming the fix if it happens.

struct MapContainer: View {

@State private var session: MapSession?

var body: some View {
if let session {
MapScreen(session: session)
} else {
ProgressView()
.task {
session = try? await MapSession(mapID: 19158, token: "YOUR_TOKEN")
}
}
}
}

One session can feed several views at once — a Map and a WemapGeoARSDK AR view, for instance. A map view is bound to exactly one session for its whole life, so passing a different session rebuilds the map; the SDK keys that itself and you never write .id(_:) for it.

The map view is a handle, not view state​

The MapView from onLoaded exists so a control outside the map can call into the SDK. Nothing in your body derives from it, which is why three rules apply:

  • Declare the @State in the same view as the Map. In a parent that outlives a conditionally-shown map, it keeps the dismantled map view alive and delays its teardown until the parent goes.
  • Clear it when you change session. The old map view stays functional but is no longer on screen, so calls on it quietly affect nothing.
  • In a bigger app, hold it weak from a view model — starting a navigation is app logic, not view state. It is only valid while the Map is on screen, because nothing else retains the view.

Everything reached through the handle is non-optional: holding it at all proves the map finished loading.

Observing​

Observation modifiers compose — applying one twice runs both handlers, so a wrapper view can add its own without stomping yours.

ModifierDelivers
onLoaded(_:)the loaded map view, once
onFailed(_:)the failure, if loading fails
onPhaseChange(_:)every LoadPhase transition
onTouch(_:)taps that did not select a point of interest
onCameraChange(frequency:_:)the MapCameraState when the camera changes
onProxyUpdate(frequency:_:)a MapProxy when the camera changes

MapProxy is a read-only view onto the camera and geometry — coordinate conversion, visible bounds, and whether the initial camera has been applied. It is snapshotted at access time, so read it when you need it rather than storing it.

onCameraChange and onProxyUpdate default to onEnd, which delivers once the map settles. continuous also delivers during animation and scrolling, so a handler that writes @State will re-evaluate your body on every frame — use it deliberately.

Binding​

Two-way bindings keep your state and the map's in step, in both directions. Unlike the observation modifiers, a binding is single: applying one twice keeps only the last, because two bindings would be two sources of truth for the same write.

BindingDirection
cameraPosition(_:)both — the map writes idle and followUser, see below
activeLevel(_:)both — nil when no building is focused
selectedPOIs(_:)both
focusedBuilding(_:)map → your state
navigationInfo(_:)map → your state, reset to nil when the navigation stops
Map(session: session)
.focusedBuilding($building)
.activeLevel($level)

if let building {
Picker("Level", selection: $level) {
ForEach(building.levels, id: \.self) { level in
Text(level.name).tag(Level?.some(level))
}
}
.pickerStyle(.segmented)
}

Selecting through selectedPOIs never moves the camera — a binding write is state, not a user action. Call centerToPOI(_:animated:zoom:) on the map view when you want the map to move.

The camera​

cameraPosition(_:) binds a MapCameraPosition: what the camera should do, not where it is. Write a position and the map carries it out:

PositionWhat the map does
automaticframes the map data, as it does when it opens
camera(_:)moves to that camera
fit(_:insets:)frames those bounds, clear of the insets
followUser(bearing:)follows the user until something else moves the camera
idlenothing: the camera stays where it is
@State private var position: MapCameraPosition = .automatic

Map(session: session)
.cameraPosition($position)

Button("Show the entrance") {
withAnimation { position = .camera(MapCameraState(center: entrance, zoom: 18)) }
}

A write inside withAnimation moves the camera with the map's own animation; the SwiftUI animation's curve and duration are not applied to the camera. Any other write moves it at once.

The map writes into the binding only when the position itself changes, never to report where the camera is:

  • idle when something other than the position moves the camera — the user's gesture, an interrupted animation, a level change while following, or code moving the camera through the map view or a widget. The camera stays where that left it.
  • followUser when the SDK starts following the user on its own, as startNavigation does.

So a position you write again after idle moves the map back — that is how a "recenter" button works — while writing the same position twice in a row does nothing.

Button {
withAnimation { position = .followUser(bearing: .heading) }
} label: {
Image(systemName: position == .followUser(bearing: .heading) ? "location.fill" : "location")
}

To read the camera — to show it, or keep it and restore it later as .camera(saved) — use onCameraChange(frequency:_:). MapCameraState is Codable, so a camera can be kept wherever Data can, and goes inside your own Codable types without any code:

@SceneStorage("camera") private var savedCamera: Data?

var body: some View {
let saved = savedCamera.flatMap { try? JSONDecoder().decode(MapCameraState.self, from: $0) }

Map(session: session)
.initialCameraPosition(saved.map { .camera($0) } ?? .automatic)
.onCameraChange { savedCamera = try? JSONEncoder().encode($0) }
}

With a cameraPosition(_:) binding, start the bound position at .camera(saved) instead — a bound position's first value wins over initialCameraPosition.

The encoding holds the center, zoom, bearing and pitch, under keys that stay valid throughout 1.x, so a camera saved by one version of your app decodes in the next.

MapCameraState is a value type — center, zoom, bearing, pitch, and why it last moved. Two states are equal when their center, zoom, bearing and pitch are equal, exactly; lastChangeReason is not compared. A camera you apply comes back from the map a few ULPs off, so compare positions, not cameras, to tell what the map is doing.

Only need an opening position? Don't take a binding at all:

Map(session: session)
.initialCameraPosition(.camera(MapCameraState(center: entrance, zoom: 18)))

A binding and initialCameraPosition do not combine — a bound position's first value opens the map. Either way the opening position replaces the camera the map data declares.

Waiting for the camera​

The camera can only be applied once the view has a real size, which in SwiftUI can happen after loading finishes. Await it rather than polling the view's bounds:

.onLoaded { mapView in
Task {
try? await mapView.awaitInitialCamera()
print("Opened at \(mapView.proxy.camera.center)")
}
}

Subclassing the map view​

If you subclass MapView, build it yourself:

Map(session: session) { frame, session, config in
MyMapView(frame: frame, session: session, config: config)
}

Naming​

The view is called Map, following MapboxMaps.Map and MapKit.Map. If you import both MapKit and WemapMapSDK without qualification, disambiguate with WemapMapSDK.Map.