Pergunta

So from the multiple answers I see on here this is how to center and zoom on user location when the app loads and it works great.

-(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];

}

But when you start playing with the map every time this delegate method gets called it brings me back to user location. How do i deal with this should i stop user location updates? Ive tried putting this code in view did load just so I get the initial zoom and center but it doesn't work? Or maybe i can put the code in another map kit delegate method i just don't know the proper one do it in. How does everyone else do this?

Foi útil?

Solução

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

Is a mapKit delegate method called each time the user's location has changed. Which is why your map will center on user's location on every call. You can't use that in order to init the map on user's position when app is launched.

I think if it's not working on viewDidLoad it's because at that time the user's location is not yet known by the app. Put a breakpoint there and see for yourself.

For me you should add an observer in viewDidLoad that is called when the app gets the data on the user's location

// 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];
}

Then in

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

Wait for the keyPath "location" to get called. When it's trigger for the first time, the view is loaded and the app knows the user's location. You can then put your code to center the map on user's position. But then make sure to remove the observer so it doesn't get call more than one time.

[self.mapView.userLocation removeObserver:self
                                   forKeyPath:@"location" context:NULL];
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top