swiftmapkituserlocationmkuserlocationshowuserlocation

How to set Mapkit user tracking button state


I've created a map with a user tracking button on the top right corner. I was wondering how I would be able to set the state to "followWithHeadlights" by default on load so that it follows the users current position just like you would have on GPS?

Current behaviour on load: Button current behaviour

Desired behaviour on load: Button desired behaviour

Code snippet:

func setUserTrackingButton() {

    // Mapkit tracking button
    let trackingButton: MKUserTrackingBarButtonItem = MKUserTrackingBarButtonItem.init(mapView: mapView)
    trackingButton.customView?.tintColor = UIColor(red:0.01, green:0.81, blue:0.37, alpha:1.0)
    trackingButton.customView?.frame.size = CGSize(width: 50, height: 50)

    let toolBarFrame = CGRect(origin: CGPoint(x: 0, y: 0) , size: CGSize(width: 50, height: 50))
    let toolbar = UIToolbar.init(frame: toolBarFrame)
    toolbar.barTintColor = UIColor.white
    toolbar.isTranslucent = true
    let flex: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
    toolbar.items = [flex, trackingButton, flex]

    let origin = CGPoint(x: self.view.frame.size.width - 85, y: 60)
    let roundedSquare: UIView = UIView(frame: CGRect(origin: origin, size: CGSize(width: 50, height: 50)))
    roundedSquare.backgroundColor = UIColor.white
    roundedSquare.layer.cornerRadius = 5
    roundedSquare.layer.masksToBounds = true

    roundedSquare.addSubview(toolbar)
    mapView.addSubview(roundedSquare)
}

ViewDidLoad includes:

mapView.setUserTrackingMode(MKUserTrackingMode.followWithHeading, animated: true)

Thanks!


Solution

  • The user tracking mode must be set after the map view has fully loaded. In viewDidLoad this is not the case.

    You can use the MKMapViewDelegate method mapViewDidFinishLoading(mapView:) to know when the map has loaded:

    class MyMapViewController: UIViewController, MKMapViewDelegate {
    
        // ...
    
        override func viewDidLoad() {        
            super.viewDidLoad()
    
            // ...
            mapView.delegate = self
        }
    
        // ...
    
        func mapViewDidFinishLoadingMap(_ mapView: MKMapView) {
            mapView.setUserTrackingMode(.followWithHeading, animated: true)
        }
    
        // ...
    
    }