1

I'm trying to change the pitch to be more and more angled as the user zooms in, but I have a suspicion it's because the .cameraChanged event is firing fast all the time, so the app crashes on the initial map load. Any suggestions on figuring out how to make this work?

override public func viewDidLoad() {
    let myResourceOptions = ResourceOptions(accessToken: "pk.ey###################")
    let myCameraOptions = CameraOptions(center: appState.myLocation.coordinate, zoom: 12)
    let myMapInitOptions = MapInitOptions(resourceOptions: myResourceOptions, cameraOptions: myCameraOptions, styleURI: StyleURI(url: URL(string: "mapbox://styles/myaccount/myMap")!)!)
    let myCameraBoundsOptions = CameraBoundsOptions(maxZoom: 18.5, minZoom: 11, maxPitch: 60, minPitch: 0)

    do {
        try mapView.mapboxMap.setCameraBounds(with: myCameraBoundsOptions)
        mapView.mapboxMap.onNext(event: .mapLoaded) { _ in
            // add sources, layers, etc
        }

        mapView.mapboxMap.onEvery(event: .cameraChanged, handler: { [weak self] _ in
            guard let self = self else { return }
            let pitch = ((self.mapView.mapboxMap.cameraState.zoom - self.mapView.mapboxMap.cameraBounds.minZoom)/(self.mapView.mapboxMap.cameraBounds.maxZoom - self.mapView.mapboxMap.cameraBounds.minZoom)) * 60
            let options = CameraOptions(pitch: pitch)
            self.mapView.mapboxMap.setCamera(to: options)
        })
    }
}
nickcoding2
  • 142
  • 1
  • 8
  • 34

1 Answers1

0

by setting new pitch will result in another cameraChanged event, this will lead to an infinite loop and crash the program. What you can do to avoid this is to have a flag on when to set new pitch, for example:

final class MapViewController: UIViewController {

    var mapView: MapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        mapView = MapView(frame: view.bounds)
        mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        view.insertSubview(mapView, at: 0)

        // Code to config map

        mapView.mapboxMap.onEvery(event: .cameraChanged) { [unowned self] _ in
            guard !self.ignoresCameraChangedEvent else { return }

            let pitch = 60 * (self.mapView.mapboxMap.cameraState.zoom - self.mapView.mapboxMap.cameraBounds.minZoom)/(self.mapView.mapboxMap.cameraBounds.maxZoom - self.mapView.mapboxMap.cameraBounds.minZoom)
            self.changeCameraWithoutNotification(CameraOptions(pitch: pitch))
        }
    }

    private var ignoresCameraChangedEvent = false
    private func changeCameraWithoutNotification(_ newCamera: CameraOptions) {
        ignoresCameraChangedEvent = true
        mapView.mapboxMap.setCamera(to: newCamera)
        ignoresCameraChangedEvent = false
    }
}
Mai Mai
  • 614
  • 5
  • 10