Member-only story
Working with MapKit in SwiftUI
This year, at WWDC2023, Apple announced a new set of MapKit APIs that works a lot better together with SwiftUI.
Let's explore some cool stuff we can achieve if we plan to include a map experience into our app.
Creating a Map
We can include a simple map by creating a Map
instance in our view. This will create a default map.
If we want to add some components to our map, we must use MapContentBuilder
. Inside the closure, we can create any MapContent
component we need.
struct MapContainerView: View {
var body: some View {
Map {
// MapContent
}
}
}
Adding Markers & Annotations
Markers are used to display a specific coordinate in the map. They have a specific UI (balloon shape) that we can not control. However, it's a good alternative if we only need to highlight some coordinates.
extension CLLocationCoordinate2D {
// Some place in Miami
static let coffeeShopCoordinate = CLLocationCoordinate2D(latitude: 25.865208, longitude: -80.121807)
}
struct MapContainerView: View {
var body: some View {
Map {
Marker("Coffee Shop", coordinate: .coffeeShopCoordinate)
}
}
}