Objective-c – MKMapView: On startup user location -> zooming

iphoneobjective c

I have a MKMapView and in the Map View "Show User Location" is set. The question if the app should use my location, I say yes. Then I see the blue bullet and I can zoom to the current location.

I read many other posts about this, but nothing solve the problem, that the user location won't zoom in automatically.

I want to have a zoom on startup if the user allows access the location, otherwise a defined coordinate should zoom in. (after, is the use allows the location, it can be updated, but should not set the center to the user location everytime I get updates on the location).

What are the steps to implement this behavior? I tried for example this: How do I zoom an MKMapView to the users current location without CLLocationManager? with the KVO but it does not work…

I hope someone has an idea?

Best Regards, Tim

Best Answer

Have you tried the delegate method mapView:didUpdateUserLocation:?

I used something like this in my code:

In the .h file:

@property (nonatomic, retain) CLLocation* initialLocation;

And in the .m file:

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    if ( !initialLocation )
    {
        self.initialLocation = userLocation.location;

        MKCoordinateRegion region;
        region.center = mapView.userLocation.coordinate;
        region.span = MKCoordinateSpanMake(0.1, 0.1);

        region = [mapView regionThatFits:region];
        [mapView setRegion:region animated:YES];
    }
}