mapView不使用didUpdateUserLocation进行第二次尝试
我从mainviewcontroller按下视图贴图按钮时,我正在加载mapviewcontroller:
- (IBAction)mapButton:(id)sender { MapKitDisplayViewController *mapKitDisplayView = [[MapKitDisplayViewController alloc] init]; [self presentModalViewController:mapKitDisplayView animated:YES]; [mapKitDisplayView release]; mapKitDisplayView = nil; }
在启动此地图视图时,将调用此方法,该方法可正确缩放到用户位置:
- (void)mapView:(MKMapView *)myMapView didUpdateUserLocation:(MKUserLocation *)userLocation { myMapView.showsUserLocation = YES; NSLog(@"didUpdateUserLocation = '%@'", userLocation); MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance([userLocation coordinate], 20000, 20000); [myMapView setRegion:region animated:YES]; }
我在这个屏幕上有一个完成按钮,可以解除这个视图:
- (IBAction)mapDoneButton:(id)sender { [self dismissModalViewControllerAnimated:YES]; }
在此阶段,用户将被带回主视图控制器,但是当我再次按下视图贴图按钮时,永远不会调用didUpdateUserLocation方法! 因此,地图视图缩小为默认视图,并且不会像以前一样放大。
我怎样才能让它再次被召唤?
谢谢
MKMapView
对象不会自动触发用户位置的更新。 您需要通过设置showsUserLocation = YES
来激活搜索。 然后,这将获取用户的位置,然后调用委托方法mapView:didUpdateUserLocation:
. 因此,在viewWillAppear:
上将此值设置为YES
viewWillAppear:
一旦您拥有了用户位置,就可以将其设置为NO
以停止跟踪用户。 如果不这样做,它会定期更新用户位置并调用委托方法。 如果不这样做,用户位置应该是不可靠的。
我接下来做的是:
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{ [[NSNotificationCenter defaultCenter] postNotificationName:@"gotUserLocation" object:self];}
然后在viewDidLoad中检查用户位置是否可用。 如果它不是注册视图控制器作为该通知的接收者:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(zoomToLocation) name:@"gotUserLocation" object:nil];
如果用户位置可用,则只需调用zoomToLocation方法