简体   繁体   中英

MapView not zooming to user location

My mapview is not zooming to my user location. Please can you point out the error:

- (void)viewDidLoad {
[super viewDidLoad];
mapView = [[MKMapView alloc] init];
mapView.showsUserLocation = YES;
mapView.mapType = MKMapTypeHybrid;
mapView.delegate = self;

[self performSelector:@selector(startupZoom) withObject:nil afterDelay:1.25];
}
- (void)startupZoom {
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta=0.2;
span.longitudeDelta=0.2;
CLLocationCoordinate2D location=mapView.userLocation.coordinate;
location.latitude=mapView.userLocation.coordinate.latitude;
location.longitude=mapView.userLocation.coordinate.longitude;
region.span=span;
region.center=location;
[mapView setRegion:region animated:TRUE];
[mapView regionThatFits:region];
NSLog(@"%f, %f", mapView.userLocation.coordinate.latitude, mapView.userLocation.coordinate.longitude);
}

The mapView is being created but its frame is not set and it's not being added as a subview of the view controller's view.

Change the alloc+init line to (change the dimensions as needed):

mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 300)];

Then before the performSelector line, add this:

[self.view addSubview:mapView];

Note however that it's better to use the MKMapView's didUpdateUserLocation delegate method to zoom to the user's location instead of assuming the user location will be available after some arbitrary, fixed interval like 1.25 seconds.

For example, remove the performSelector line and implement didUpdateUserLocation:

- (void)mapView:(MKMapView *)mapView 
            didUpdateUserLocation:(MKUserLocation *)userLocation
{
    [self startupZoom];
}

Only possible problem using the didUpdateUserLocation method is that it will be called every time the user's location changes so if you only want to zoom once on startup, you'll need to add a BOOL flag ivar and check/set it accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM