Animate the camera

CameraAnimation

This example demonstrates how to animate the camera.

You will learn the following:

  • Respond to map events
  • How to create a camera that rotates around the center point

Respond to map events

We need to set animated camera in the MapView after MapView has been loaded. If order to to respond to map events, for example perform an action after MapView initialization finished. In SwiftUI, a Coordinator can be used with delegates, data sources, and user events. The UIViewRepresentable protocol defines makeCoordinator() method which creates coordinator instance. Add the following code to declare coordinator class:

     class Coordinator: NSObject, MGLMapViewDelegate {
        var control: CameraAnimationMapView
        
        init(_ control: CameraAnimationMapView) {
            self.control = control
        }

        func mapViewDidFinishLoadingMap(_ mapView: MGLMapView) {
            // Wait for the map to load before initiating the first camera movement.

            // Create a camera that rotates around the same center point, rotating 180°.
            // `fromDistance:` is meters above mean sea level that an eye would have to be in order to see what the map view is showing.
            
            let camera = MGLMapCamera(
                    lookingAtCenter: mapView.centerCoordinate,
                    altitude: 4500,
                    pitch: 15,
                    heading: 180)

            // Animate the camera movement over 5 seconds.
            
            mapView.setCamera(
                    camera,
                    withDuration: 5,
                    animationTimingFunction: CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut))
        }
    }

And then add the following method to the SwiftUI view:

    func makeCoordinator() -> CameraAnimationMapView.Coordinator {
        Coordinator(self)
    }

And finally set the reference coordinator on mapbox map view

CameraAnimation.delegate = context.coordinator

Set animated camera

In the Coordinator class we implemented func mapViewDidFinishLoadingMap(_ mapView: MGLMapView) method. In that method, we create a camera that rotates around the same center point, rotating 180°.

   let camera = MGLMapCamera(
                    lookingAtCenter: mapView.centerCoordinate,
                    altitude: 4500,
                    pitch: 15,
                    heading: 180)

Then we instruct the MapView to use the animated camera.

mapView.setCamera(
                    camera,
                    withDuration: 5,
                    animationTimingFunction: CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut))
iOS SDK

SDK JS Reference

On this page