简体   繁体   中英

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 MkMapView 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.

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