MapKit

Basic Map (Region)

Display a map by binding a coordinate region. Import MapKit to use Map in SwiftUI.

Syntax:

  • @State private var position: MapCameraPosition = .region(MKCoordinateRegion(...))
  • Map(position: $position)

Example

BasicMap.swift

ContentView.swift

App.swift

import SwiftUI
import MapKit

struct BasicMap: View {
  @State private var position: MapCameraPosition = .region(
MKCoordinateRegion(
  center: CLLocationCoordinate2D(latitude: 37.3349, longitude: -122.0090),
  span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
)
) var body: some View {
Map(position: $position)
  .ignoresSafeArea()
} }

This example centers the map on Apple Park with a modest zoom.


Annotations

Add markers or custom annotations at specific coordinates.

Syntax:

  • @State private var position: MapCameraPosition = .region(MKCoordinateRegion(...))
  • Map(position: $position) { Marker("Title", coordinate: ...) }
  • Annotation("Title", coordinate: ...) { View }

Example

Markers.swift

ContentView.swift

App.swift

import SwiftUI
import MapKit

struct MarkersMap: View {
  @State private var position: MapCameraPosition = .region(
MKCoordinateRegion(
  center: CLLocationCoordinate2D(latitude: 37.3349, longitude: -122.0090),
  span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
)
) let places = [
("Park", CLLocationCoordinate2D(latitude: 37.3349, longitude: -122.0090)),
("Cafe", CLLocationCoordinate2D(latitude: 37.3327, longitude: -122.0053))
] var body: some View {
Map(position: $position) {
  ForEach(places, id: \.0) { name, coord in
    Marker(name, coordinate: coord)
  }
}
} }

This example adds two simple markers around the region.


Open in Maps

Use MKMapItem to open a location or directions in the Apple Maps app.

Syntax:

  • let item = MKMapItem(placemark:)
  • item.openInMaps(launchOptions:)

Example

OpenMaps.swift

ContentView.swift

App.swift

import MapKit

func openDirections() {
  let dest = MKMapItem(placemark: MKPlacemark(coordinate: .init(latitude: 37.3349, longitude: -122.0090)))
  dest.name = "Apple Park"
  dest.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving])
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *