开发者

iPhone MkMapView lock center to userlocation

I have a MkMapView and want to keep the Map centered to the user's location, exaclty as the iPhone Map Application does when you press the scope button.

I am using the setCenterCoordinate method because I don't need to set the zoom. I use it everytime the location is updated from the location manager.

The problem is that as it updates at every half a second (aprox), this method "setCenterCoordinate" is called all the time and the App gets Kind of hung. If I need to switch to a tab away from the map view I have to keep pressing the other tab to accomplish that.

Well, all this text just to ask if there's a proper way to make the M开发者_如何学CkMapView get it's center set to the user location (blue dot).

Thanks


I've already described a better way for getting updates of userLocation.location property of MKMapView through KVO notifications instead of using another location manager. How do I zoom an MKMapView to the users current location without CLLocationManager?

Of course, you should make some changes to the method that receive KVO notifications. Something like that:

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

    if ([self.mapView isUserLocationVisible]) {  
       [self.mapView setCenterCoordinate:self.mapView.userLocation.location.coordinate
                                animated:YES];
    }
}

I've tested this code and it works fine.


In addition to ddnv's answer:

Never forget to stop the observer in the ViewController's viewWillDisappear (or viewDidUnload in < iOS 6.0) method like that:

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

Otherwise, your app will crash hard.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜