How to add a map to a SwiftUI view

Asked on 07/30/2024

1 search

To add a map to a SwiftUI view, you can use the MapKit framework. Here's a basic example of how to do it:

  1. Import MapKit: First, make sure to import the MapKit framework in your SwiftUI view file.

    import SwiftUI
    import MapKit
    
  2. Create a Map View: You can create a Map view and configure it with the necessary properties.

    struct ContentView: View {
        @State private var region = MKCoordinateRegion(
            center: CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194),
            span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
        )
    
        var body: some View {
            Map(coordinateRegion: $region)
                .frame(height: 300)
        }
    }
    
  3. Run the App: This will display a map centered on the specified coordinates (in this case, San Francisco).

For more advanced usage, such as displaying place details or using place identifiers, you can refer to the session Unlock the power of places with MapKit from WWDC 2024. This session covers how to reference places using an identifier, show details about a place in your app's UI, and find places effectively using enhancements to the search APIs.

Relevant Sessions

These sessions provide a comprehensive overview of integrating maps and other advanced features into your SwiftUI applications.

How to add a map to a SwiftUI view | Ask WWDC