Using MapKit with SwiftUI

Learn how to use Maps in your SwiftUI app and how to add annotations to the MapView as markers, pins or custom annotations.

Using MapKit with SwiftUI

Even though Maps are not yet as powerful in SwiftUI in comparison to their UIKit counterparts, basic map functionality is easy to implement in SwiftUI. In a series of articles, we want to share the most common use cases for maps and how they can be implemented with the latest and greatest additions to SwiftUI.

Use a Map to display a map

Starting with an empty Xcode project for a SwiftUI app, you can edit the ContentView.swift file with just a few lines of code to add an interactive map. In our example, however, we created a MapView.swift file, but it works all the same. To display a map with the region of your choosing, follow these steps:

  1. import MapKit
  2. Add a @State property to define a variable named region as a MKCoordinateRegion that specifies the center coordinate and zoom level for the map.
  3. Add a Map element to the body of the MapView and use the region as a parameter.

The parameter has to be provided as a $region binding, so the map would update if the region variable changes. With a .edgesIgnoringSafeArea(.all) modifier, the Map can be adjusted to expand over the safe area and fill the entire screen.

import SwiftUI
// 1.
import MapKit

struct MapView: View {
    // 2.
    @State private var region = MKCoordinateRegion(
				center: CLLocationCoordinate2D(
					latitude: 40.83834587046632, 
					longitude: 14.254053016537693),
				span: MKCoordinateSpan(
                	latitudeDelta: 0.03,
                    longitudeDelta: 0.03)

    var body: some View {
		// 3.
		Map(coordinateRegion: $region)

Let's now see, how we can add annotations to the map. Become a free member or log in to proceed.