Question

I am using am mapview and sometimes my map will zoom onto my users location when I open it but sometimes it will zoom to the middle of an ocean. I don't know what is causing this, this is the code I am using for zooming. I don't want the map to track the user but just zoom to their location once they open the map

-(void) viewDidAppear:(BOOL)animated{

MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(self.mapView.userLocation.coordinate, 600.0f, 600.0f);
[self.mapView setRegion:region animated:YES];

 }

 -(void) viewDidLoad{

[super viewDidLoad];

self.mapView.delegate = self;
[self.mapView setShowsUserLocation:YES];

 }
Was it helpful?

Solution

I encountered this issue before. It seems that mapView is slow to load and detect user location sometimes, resulting in your code in viewDidAppear being executed before the map view can check user's location. Thus, the spot in the ocean.

It will be better to use mapView's delegate to display user location when it's ready:

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    if(isShowUserLocation)
    {
        MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 600.0, 600.0);
        [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
        isShowUserLocation = NO;
    }
}

Set isShowUserLocation = YES in viewDidLoad. This ensures the user location is shown once on entry and also selectively when you need it.

Edit 1:

@implementation MapViewController
{
    BOOL isShowUserLocation;
}

-(void) viewDidLoad
{
    [super viewDidLoad];
    self.mapView.delegate = self;
    [self.mapView setShowsUserLocation:YES];
    isShowUserLocation = YES;
}

Edit 2:

Alternatively, use CLLocationManager - see this post. It allows you stop the updating. Do include CoreLocation.framework. You may need to handle some nitty-gritty issues when interacting CLLocationManager with MapView though.

OTHER TIPS

When you pass 0's for lat and long, you will git a spot in the middle of the ocean south of Ghana in Africa.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top