With the MKMapView
there's an option called "Show users current location" which will automatically show a users location on the map
.
I'd like to move and zoom to this location when it's found (and if it changes).
The problem is, there doesn't appear to be any method called when the user location is updated on the map
, so I have nowhere to put the code that will zoom/scroll
.
Is there a way to be notified when an MKMapView
has got (or updated) the user location so I can move/zoom to it? If I use my own CLLocationManager
the updates I get do not correspond with the updates of the user marker on the map, so it looks silly when my map moves and zooms seconds before the blue pin appears.
This feels like basic functionality, but I've spent weeks looking for a solution and not turned up anything close.
You have to register for KVO notifications of userLocation.location
property of MKMapView
.
To do this, put this code in viewDidLoad:
of your ViewController or anywhere in the place where your map view is initialized.
[self.mapView.userLocation addObserver:self
forKeyPath:@"location"
options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld)
context:NULL];
Then implement this method to receive KVO notifications
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
if ([self.mapView showsUserLocation]) {
[self moveOrZoomOrAnythingElse];
// and of course you can use here old and new location values
}
}
This code works fine for me.
BTW, self
is my ViewController in this context.