keep on you
keep on you

Reputation: 310

MapView return to the current location annotation?

I'm asking my MapView to show the current location of the user that i get it from CLLocationManager using the delegate of startUpdatingLocation and also i add to the MapView some annotations but the problem is when scroll in the map to show some annotations the map return to the annotation of the current user

- (void)viewDidLoad
{
     [super viewDidLoad];

     // Get the location if the user
     _locationManager = [[CLLocationManager alloc] init];

     if ([CLLocationManager locationServicesEnabled]) 
     {
        _locationManager.delegate = self;
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
        [_locationManager startUpdatingLocation];
     }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
      // set the map view to the current location
      MKCoordinateSpan span;
      span.latitudeDelta = 0.01;
      span.longitudeDelta = 0.05;

      MKCoordinateRegion region;
      region.span = span;
      region.center = _locationManager.location.coordinate;

      [self.mapView setRegion:region animated:YES];
}

Upvotes: 0

Views: 506

Answers (2)

Sunil Zalavadiya
Sunil Zalavadiya

Reputation: 1993

You have to call following method [_locationManager stopUpdatingLocation]; like following:-

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
      [_locationManager stopUpdatingLocation];

      // set the map view to the current location
      MKCoordinateSpan span;
      span.latitudeDelta = 0.01;
      span.longitudeDelta = 0.05;

      MKCoordinateRegion region;
      region.span = span;
      region.center = _locationManager.location.coordinate;

      [self.mapView setRegion:region animated:YES];
}

because once you start updating location...it calls above function every time..so after calling this function you need to stop calling this function by calling [_locationManager stopUpdatingLocation];method.

Upvotes: 0

user467105
user467105

Reputation:

The didUpdateToLocation delegate method can be called multiple times if a more accurate or recent location is obtained or obviously if the device is moving.

Since you are setting the map's region in that delegate method unconditionally, the map will always pan back to the user location when it gets an update even after the user or the app has panned or zoomed the map somewhere else.

In that delegate method, you could have it zoom to the user location only once by adding a bool ivar to tell whether you've already zoomed.

Another option is to check the location's various properties such as timestamp or horizontalAccuracy and only return to the user location if those values are at a certain threshold.

Upvotes: 1

Related Questions