What is the best way to use MKMapCamera

3.9k views Asked by At

I've found three ways to use the MKMapCamera and I want to know which one is the most recommended one. My goal is to follow the user and I want to update the camera on each location update (so each second).

1.

            MKMapCamera *newCamera = [MKMapCamera camera];
            [newCamera setCenterCoordinate:newCoordinate];
            [newCamera setPitch:60];
            [newCamera setHeading:heading];
            [newCamera setAltitude:eyeAltitude];
            [mapView setCamera:newCamera];

2.

            MKMapCamera *newCamera = [MKMapCamera cameraLookingAtCenterCoordinate:newCoordinate
                                                             fromEyeCoordinate:oldCoordinate
                                                                   eyeAltitude:eyeAltitude];
            [newCamera setPitch:pitch];

            [mapView setCamera:newCamera];

3.

            MKMapCamera *oldCamera = mapView.camera;
            [oldCamera setCenterCoordinate:newCoordinate];
            [oldCamera setPitch:60];
            [oldCamera setHeading:heading];
            [oldCamera setAltitude:eyeAltitude];

Memory wise seems nr 3 the most decent one or is it a singleton class? In most examples they use nr1.

For nr3 I can't get the animation to work.

Thanks!

2

There are 2 answers

1
Rameshwar Gupta On

Using the MKMapCamera, you can set the orientation of a map without messing with transforms on the view or even detecting the user’s heading.

MKMapCamera *mapCamera = [[self.mvMap camera] copy];
[mapCamera setHeading:headingDegrees]; 
[self.mvMap setCamera:mapCamera animated:YES];

If you don’t want the animation, you can just set the new heading on the existing camera:

[self.mapView.camera setHeading:heading];
0
Jav Solo On

Updated answer in Swift 5

The code below worked for me without calling setCamera

let mapCamera = self.mapView.camera
mapCamera.heading = headingInDegrees
mapCamera.centerCoordinate = newCoordinate

You can also just set the new heading on the existing camera like so:

self.mapView.camera.heading = headingInDegrees