The MapKit framework provides a robust interface for embedding highly detailed, interactive Apple Maps directly into your applications.
Whether you need to show the location of a single restaurant or provide full turn-by-turn navigation overlays, MapKit handles the heavy rendering logic for you.
With recent updates to SwiftUI, implementing a fully functional map takes only a few lines of code.
To display a map in SwiftUI, you import the MapKit framework and use the Map view.
By default, an empty Map() will render an interactive map of the world that the user can pan and zoom.
import SwiftUI import MapKitstruct SimpleMapView: View { var body: some View { // Displays a full-screen interactive map Map() .edgesIgnoringSafeArea(.all) } }
Usually, you want the map to start focused on a specific city or coordinate, rather than zoomed out to the entire globe.
You can control this using a MapCameraPosition state variable.
struct FocusedMapView: View {
// Setup coordinates for San Francisco
let sfCoordinate = CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194)
// Initialize the camera state pointing at SF with a specific zoom level
@State private var position: MapCameraPosition = .region(
MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194),
latitudinalMeters: 5000,
longitudinalMeters: 5000)
)
var body: some View {
// Bind the position to the map
Map(position: $position)
}
}
A map isn't very useful without points of interest.
You can easily drop pins on the map by providing a block of content inside the Map view.
You can use a standard Marker (the classic red balloon) or an Annotation (which allows you to use custom SwiftUI views as the pin).
struct MarkerMapView: View {
let eiffelTower = CLLocationCoordinate2D(latitude: 48.8584, longitude: 2.2945)
var body: some View {
Map {
// A standard map marker
Marker("Eiffel Tower", coordinate: eiffelTower)
.tint(.purple)
}
}
}
Which MapKit element should you use if you want to display the standard, built-in red balloon icon at a specific coordinate?