Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MKMapView: On startup user location -> zooming

I have a MKMapView and in the Map View "Show User Location" is set. The question if the app should use my location, I say yes. Then I see the blue bullet and I can zoom to the current location.

I read many other posts about this, but nothing solve the problem, that the user location won't zoom in automatically.

I want to have a zoom on startup if the user allows access the location, otherwise a defined coordinate should zoom in. (after, is the use allows the location, it can be updated, but should not set the center to the user location everytime I get updates on the location).

What are the steps to implement this behavior? I tried for example this: How do I zoom an MKMapView to the users current location without CLLocationManager? with the KVO but it does not work...

I hope someone has an idea?

Best Regards, Tim

like image 772
Tim Avatar asked Apr 22 '11 16:04

Tim


2 Answers

Have you tried the delegate method mapView:didUpdateUserLocation:?

I used something like this in my code:

In the .h file:

@property (nonatomic, retain) CLLocation* initialLocation;

And in the .m file:

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    if ( !initialLocation )
    {
        self.initialLocation = userLocation.location;

        MKCoordinateRegion region;
        region.center = mapView.userLocation.coordinate;
        region.span = MKCoordinateSpanMake(0.1, 0.1);

        region = [mapView regionThatFits:region];
        [mapView setRegion:region animated:YES];
    }
}
like image 125
Joseph Lin Avatar answered Oct 16 '22 12:10

Joseph Lin


you can do it like this in your viewDidLoad write this code

self.mapDetail.showsUserLocation = YES;
[self.mapDetail.userLocation addObserver:self
                            forKeyPath:@"location"
                               options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld)
                               context:nil];

and this method will do the task

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    MKCoordinateRegion region;
    region.center = self.mapDetail.userLocation.coordinate;

    MKCoordinateSpan span;
    span.latitudeDelta  = 1; // Change these values to change the zoom
    span.longitudeDelta = 1;
    region.span = span;

    [self.mapDetail setRegion:region animated:YES];
    [self.mapDetail.userLocation removeObserver:self forKeyPath:@"location"];
}
like image 28
D-eptdeveloper Avatar answered Oct 16 '22 12:10

D-eptdeveloper