简体   繁体   English

MapView无法缩放到用户位置

[英]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. 正在创建mapView,但未设置其框架,也没有将其添加为视图控制器视图的子视图。

Change the alloc+init line to (change the dimensions as needed): 将alloc + init行更改为(根据需要更改尺寸):

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

Then before the performSelector line, add this: 然后在performSelector行之前,添加以下内容:

[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. 但是请注意,最好使用MKMapView的didUpdateUserLocation委托方法来缩放到用户的位置,而不是假设用户的位置在经过1.25秒的任意固定间隔后将可用。

For example, remove the performSelector line and implement didUpdateUserLocation: 例如,删除performSelector行并实现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. 使用didUpdateUserLocation方法的唯一可能问题是,每次用户位置更改时都会调用该方法,因此,如果您只想在启动时缩放一次,则需要添加BOOL标志ivar并进行相应的检查/设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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