J. Doe
J. Doe

Reputation: 81

iOS - MapKit camera rotation animation

I'm trying to make some fancy rotation (with pitch) animation on the MapKit. With this code

func animateCamera() {
        let newCamera: MKMapCamera? = mapView.camera
            newCamera?.pitch = 90.0
            newCamera?.heading = 180.0
            newCamera?.altitude = 200.0

        let camera: MKMapCamera? = mapView.camera
            camera?.pitch = 0.0
            camera?.heading = 360.0
            camera?.altitude = 20.0

        UIView.animate(withDuration: 3.0, delay: 0.0, options: ([.curveLinear, .beginFromCurrentState]), animations: {() -> Void in
            self.mapView.setCamera(newCamera!, animated: true);
        }, completion: {(_ finished: Bool) -> Void in
            print("has not been interrupted : \(finished)")
        })

        UIView.animate(withDuration: 3.0, delay: 3.0, options: ([.curveLinear, .beginFromCurrentState]), animations: {() -> Void in
            self.mapView.setCamera(camera!, animated: true);
        }, completion: {(_ finished: Bool) -> Void in
            print("has not been interrupted : \(finished)")
        })
 }

But when I run the function it only snaps to the given heading, pitch, and altitude WITHOUT animating. What have I missed or done wrong?

Thanks in advance!

Upvotes: 1

Views: 1399

Answers (1)

Reinier Melian
Reinier Melian

Reputation: 20804

I know that must have a better way to do this, but this is the way that I found, and works, the main problem is to know when the animation is ended, I don't found any clue about it, so i use 2 seconds as arbitrary time

func animateCamera() {
    let newCamera: MKMapCamera = MKMapCamera(lookingAtCenter: self.mapView.camera.centerCoordinate, fromDistance: 200.0, pitch: 90.0, heading: 180.0)
    self.mapView.setCamera(newCamera, animated: true)

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(2 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
        let newCamera: MKMapCamera = MKMapCamera(lookingAtCenter: self.mapView.camera.centerCoordinate, fromDistance: 20.0, pitch: 0.0, heading: 360.0)
        self.mapView.setCamera(newCamera, animated: true)
    }
}

Hope this helps you

Upvotes: 2

Related Questions