MKMapView Zooming In On User's Location Once But Not The Second Time in Tab-Bar App (iOS)

I have an MKMapView as part of a Navigation Controller in a Tab Bar based app.

I click a UIButton on the first View Controller and it pushes to the second View Controller which contains the MKMapView. When the Map View loads, it zooms in on the user's location using:

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

        MKCoordinateRegion region;
        region.center = theMapView.userLocation.coordinate;
        region.span = MKCoordinateSpanMake(2.0, 2.0);
        region = [theMapView regionThatFits:region];
        [theMapView setRegion:region animated:YES];
    }
}

When I hit the back button on the Navigation Controller above the MapView and then click back to the map, it no longer zooms in on the user's current location, but just has the full zoom out default:

Here's a picture of the view the second time.

I figure it would work correctly if I could somehow call the didUpdateUserLocation in the viewDidAppear method but I'm not sure how to pull this off since the didUpdateUserLocation is a delegate method.

Is that the right approach or is there a different approach I should take to do this? Thanks!

P.S. I've seen this question but it's slightly different with it's use of a modal view controller

Answers


I would pull all of the zooming code into its own method that can be messaged from -viewDidAppear: and -mapView:didUpdateToUserLocation:.

- (void)zoomToUserLocation:(MKUserLocation *)userLocation
{
    if (!userLocation)
        return;

    MKCoordinateRegion region;
    region.center = userLocation.location.coordinate;
    region.span = MKCoordinateSpanMake(2.0, 2.0); //Zoom distance
    region = [self.mapView regionThatFits:region];
    [self.mapView setRegion:region animated:YES];
}

Then in -viewDidAppear:...

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [self zoomToUserLocation:self.mapView.userLocation];
}

And in the -mapView:didUpdateToUserLocation: delegate method...

- (void)mapView:(MKMapView *)theMapView didUpdateToUserLocation:(MKUserLocation *)location
{
    [self zoomToUserLocation:location];
}

Need Your Help

Twitter Bootstrap error when running 'bootstrap:themed', with Mongo

ruby-on-rails mongodb twitter-bootstrap twitter-bootstrap-rails

This occurs when I try to run rails g bootstrap:themed Associations in my terminal:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.