objective-c MKMapView center on user location objective-c MKMapView center on user location objective-c objective-c

objective-c MKMapView center on user location


When you do mapView.showsUserLocation = YES;, you ask it to retrieve the user location. This doesn't happen instantly. As it takes time, the map view notifies its delegate that a user location is available via the delegate method mapView:didUpdateUserLocation. So you should adopt the MKMapViewDelegate protocol and implement that method. You should move all your zooming-in code to this method.

Setting the delegate

- (void)viewDidLoad {    [super viewDidLoad];    mapView = [[MKMapView alloc]           initWithFrame:CGRectMake(0,                                     0,                                    self.view.bounds.size.width,                                     self.view.bounds.size.height)           ];    mapView.showsUserLocation = YES;    mapView.mapType = MKMapTypeHybrid;    mapView.delegate = self;    [self.view addSubview:mapView];}

Updated delegate method

- (void)mapView:(MKMapView *)aMapView didUpdateUserLocation:(MKUserLocation *)aUserLocation {    MKCoordinateRegion region;    MKCoordinateSpan span;    span.latitudeDelta = 0.005;    span.longitudeDelta = 0.005;    CLLocationCoordinate2D location;    location.latitude = aUserLocation.coordinate.latitude;    location.longitude = aUserLocation.coordinate.longitude;    region.span = span;    region.center = location;    [aMapView setRegion:region animated:YES];}


In your interface you forgot to inherit MapViewDelegate -

#import <MapKit/MapKit.h>@interface MainViewController : UIViewController <FlipsideViewControllerDelegate, MKMapViewDelegate> {   MKMapView *mapView;}@property (nonatomic, retain) IBOutlet MKMapView *mapView;

Rest seems fine.