用户位置Mapkit ViewDidLoad

所以从我在这里看到的多个答案,这是如何中心和缩放应用程序加载时的用户位置,它的工作原理。

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{ NSLog(@"Did update user location"); MKCoordinateRegion mapRegion; mapRegion.center = mapView.userLocation.coordinate; mapRegion.span.latitudeDelta = 0.2; mapRegion.span.longitudeDelta = 0.2; [map setRegion:mapRegion animated: YES]; } 

但是,每当这个委托方法被调用时,当你开始使用地图的时候,它会把我带回到用户的位置。 我该如何处理这个应该停止用户位置更新? 我曾试图把这个代码在视图中加载,所以我得到的初始缩放和中心,但它不工作? 或者,也许我可以把代码放在另一个地图工具包委托方法,我只是不知道正确的做它在其他人如何做到这一点?

 -(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{ 

每次用户的位置发生变化时都会调用mapKit委托方法。 这就是为什么你的地图将在每次通话时都以用户的位置为中心。 在启动应用程序时,您不能使用它来启动用户位置上的地图。

我想如果它不是在viewDidLoad上工作,那是因为那时用户的位置还没有被应用程序知道。 在那里放一个断点,看看你自己。

对于我来说,您应该在viewDidLoad中添加一个观察者,当应用程序获取用户位置上的数据时调用该观察者

 // Check if user authorized use of location services if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized) { // Add observer [self.mapView.userLocation addObserver:self forKeyPath:@"location" options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) context:NULL]; } 

然后进来

 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context; 

等待keyPath“位置”被调用。 当它第一次触发,视图被加载,应用程序知道用户的位置。 然后你可以把你的代码放在用户的位置上。 但是,请确保删除观察者,以便它不会一次打电话。

 [self.mapView.userLocation removeObserver:self forKeyPath:@"location" context:NULL];