Mapbox in SwiftUI: Get a users current location
Mapbox current location in Swift for iOS apps
In my first steps in using MapBox in Swift, I followed the official tutorial to get started displaying a map for my iOS app. However, the tutorial ends with a hardcoded center coordinate, and I wanted to center the map on the users current location. After some digging, luckily it’s pretty easy and you don’t need to implement a second location manager (as you would, if you used Apple’s MapKit).
First, as with all apps that require the users location, you’ll need to add the proper permission keys in the Info.plist
. Open your plist, add a new key for “Privacy — Location When in Use Usage Description” and whatever reason you want to display to the user.
Next, you’ll set the properties on the mapView to start tracking the users location:
func makeUIView(context: UIViewRepresentableContext<MapView>) -> MGLMapView {mapView.delegate = context.coordinator
mapView.userTrackingMode = .followWithHeading
mapView.showsUserLocation = true
mapView.showsUserHeadingIndicator = truereturn mapView}
Finally, to actually update the map, you need to implement the proper delegate function. Nicely theMGLMapView
already has a built in MGLLocationManager
. Just implement the didUpdateUserLocation
method in your Coordinator class:
func mapView(_ mapView: MGLMapView, didUpdate userLocation: MGLUserLocation?) {guard let coord = userLocation?.coordinate else { return }mapView.setCenter(coord, animated: true)}
Done! Your map will now follow the user’s location.