NotaGeek NotaGeek - 3 months ago 10x
iOS Question

How to set zoom level to user location in MapView

Im using MKMapView to get the users location and when the view loads it shows the whole world view. Is there anyway that I can set a zoom level so that the users don't have to keep zooming in always to get the city view or street view...It would be a great help. I've posted my code below for reference...

- (void)viewDidLoad

[super viewDidLoad];
[ self.mapView.delegate self];
[self.mapView setShowsUserLocation:YES];
// Do any additional setup after loading the view, typically from a nib.

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

CLLocationCoordinate2D loc = [userLocation coordinate];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(loc, 500, 500);
[self.mapView setRegion:region animated:YES];


- (void)viewDidUnload {
[super viewDidUnload];
[_mapView setShowsUserLocation:NO];


The code you've posted should work for the most part except for this critical line in viewDidLoad:

[ self.mapView.delegate self];

Essentially, this line does nothing.
It is not setting the map view's delegate property (which is what I assume it is supposed to do).

What it is actually doing is calling self on the delegate property.

The map view's delegate is not getting set (it stays nil) and so the didUpdateUserLocation delegate method never gets called and so the map is not zooming to the user's location.

The line should be this:

[self.mapView setDelegate:self];

or even simpler:

self.mapView.delegate = self;

Note that in iOS 5 or later, you can just set userTrackingMode and the map view will automatically zoom to and follow the user's location so you don't have to do it manually.

Also note that since iOS 6, viewDidUnload is deprecated and is not even called by the OS. You probably want to move the disabling of showsUserLocation to viewWillDisappear (and move the enabling to viewWillAppear).