How to Display the User’s Location on a Map in SwiftUI
It’s simple but the approach might be new to you
Recently I had the task of showing the user's location on a map in SwiftUI. While the solution is quite simple, it took me long enough to figure out that I thought others may benefit from a post explaining how to do it.
First let's make a view model with an instance of CLLocationManager. In the initializer we will do the required steps of requesting permission to get the user's location by calling requestWhenInUseAuthorization and then actually getting their location by calling startUpdatingLocation.
import SwiftUI
import MapKit
import Observation
@Observable
class ContentViewModel {
private let locationManager = CLLocationManager()
init () {
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
}
Next we will go to the Info.plist file and add a value for the "Privacy - Location When In Use Usage Description" key. This value explains why we need the user's location.
Before we leave our view model, let's create a MapCameraPosition to hold the initial position for our Map. I chose lovely downtown Chicago.
@Observable
class ContentViewModel {
let initialPosition = MapCameraPosition.region(
MKCoordinateRegion(
center: CLLocationCoordinate2D(latitude: 41.88, longitude: -87.62),
span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
)
)
private let locationManager = CLLocationManager()
init () {
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
}
Now we move to our SwiftUI View. Let's start here by creating an instance of our view model.
import SwiftUI
import MapKit
import Observation
struct ContentView: View {
@State private var viewModel = ContentViewModel()
var body: some View { ... }
}
Finally, we make the Map and give it whatever position data you wish, I chose lovely downtown Chicago. Don't forget to import MapKit. The last step is what was new for me and may be new for you. We need to use an instance of the UserAnnotation type to show the user's location on the map. We put the instance inside the Map's MapContentBuilder content closure along with any other markers we want to show.
import SwiftUI
import MapKit
import Observation
struct ContentView: View {
@State private var viewModel = ContentViewModel()
var body: some View {
Map(initialPosition: viewModel.initialPosition) {
UserAnnotation()
// Show other locations on map
}
}
}
Want to connect?
Contact me to talk about this article, working together or something else.