Search code examples
iosmkmapviewios6ios6-maps

MKMapView not updating with calls to setRegion:animated


I'm trying to learn how to use MKMapView and have created a sample application to do so; however, in my code I'm making a call to setRegion:animated to change the center point and the span, but the map never updates. I've run through a few threads on StackOverflow (SO) where others have mentioned similar problems and tried implementing their solutions to no avail.

Things I made sure to try in my code based on other's SO threads I found:

  • Ensure I initialized the MKMapView with a frame
  • Tried running the setRegion:animated method call on the main thread

My included my code below, can anyone shed some light on why my MKMapView instance will not update it's view?

EDIT: Correct code shown below: MK_ViewController.h:

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>

@interface MV_ViewController : UIViewController {
    IBOutlet MKMapView *myMapView;
    MKCoordinateRegion defaultRegion;
    CLLocationCoordinate2D defaultCenter;
    MKCoordinateSpan defaultSpan;
}

@end

MK_ViewController.m:

#import "MV_ViewController.h"

@interface MV_ViewController ()

@end

@implementation MV_ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    // initialize default map view properties
    defaultCenter = CLLocationCoordinate2DMake(33.732894,-118.091718);
    defaultSpan = MKCoordinateSpanMake(0.028270, 0.0465364);

    // Setup MapView's inital region
    defaultRegion = MKCoordinateRegionMake(defaultCenter, defaultSpan);

    // create the map view
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    myMapView = [[MKMapView alloc] initWithFrame:screenRect];

}

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    // update map's initial view
    [myMapView setRegion:defaultRegion animated:YES];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

MK_ViewController+MKMapViewDelegate.m:

#import "MV_ViewController.h"

@implementation MV_ViewController (MKMapViewDelegate)

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
    MKCoordinateRegion region = mapView.region;
    CLLocationCoordinate2D center = region.center;
    MKCoordinateSpan span = region.span;

    NSLog(@"Center (lat,lon): (%f,%f)",center.latitude,center.longitude);
    NSLog(@"Span (lat,lon): (%f,%f)",span.latitudeDelta,span.longitudeDelta);
}

@end

Solution

  • I solved the issue by removing the MKViewMap object from the NIB, and instead added it using the following code in the MK_ViewController.m file:

    [self.view addSubView:myMapView];
    

    The issue was that the NIB wasn't properly wired up to the view controller, and the view controller was creating it's own map view.

    Thank you @Jason Cabot for pointing me in the right direction.