How to prevent rotation on MKMapView, but show the title?

For my project, I would like to put the MKMapView user header without turning the map (with a blue cone).

enter image description here

Here is the gist

Also, with permission, mapView.setUserTrackingMode(MKUserTrackingMode.FollowWithHeading, animated: true)I cannot navigate my map.

I tried to install trackingModeon mapView:didChangeUserTrackingMode, but it does not work.

Any idea?

+4
source share
1 answer

I had the same problem and resolved it with a method CLLocationManagerand locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading):

class MyViewController: UIViewController {

    @IBOutlet weak var mapView: MKMapView!
    weak var userAnnotationView: MKAnnotationView?
    var locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        mapView.showsUserLocation = true
        mapView.delegate = self
        locationManager.delegate = self
        locationManager.startUpdatingHeading()
    }
}

// MARK: - MKMapViewDelegate
extension MyViewController: MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        if let annotation = annotation as? MKUserLocation {
            // User
            let reuseIdentifier = "UserAnnotationView"
            let annotationView: MKAnnotationView
            if let view = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier) {
                annotationView = view
            } else {
                annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseIdentifier)
            }
            annotationView.image = UIImage(named: "userLocationWithoutHeading")
            userAnnotationView = annotationView
            return annotationView
        } else {
            return nil
        }
    }
}

// MARK: - CLLocationManagerDelegate
extension MyViewController: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
        guard let userAnnotationView = userAnnotationView else { return }
        userAnnotationView.image = UIImage(named: "arrowUp")
        let rotationAngle = heading.magneticHeading * Double.pi / 180.0
        userAnnotationView.transform = CGAffineTransform(rotationAngle: CGFloat(rotationAngle))
    }
}
0
source

All Articles