views:

883

answers:

1

If i want to show userLocation on the map, and at the same time record the user's location, is it a good idea to add an observer to userLocation.location and record the locations, OR should i still use CLLocationManager for recording user location and use mapView.showUserLocation to show the user's current location (blue indicator)? I want to show the default blue indicator supported by the MapKit API.

Also, here's a rough sample code:

- (void)viewDidLoad {
    ...

    locationManager = [[CLLocationManager alloc] init]; 
    locationManager.desiredAccuracy = kCLLocationAccuracyBest; 
    locationManager.distanceFilter = DISTANCE_FILTER_VALUE;
    locationManager.delegate = self; 
    [locationManager startUpdatingLocation];

    myMapView.showUserLocation = YES;
    [myMapView addObserver:self forKeyPath:@"userLocation.location" options:0 context:nil];

    ...
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    // Record the location information
    // ...
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { 
    NSLog(@"%s begins.", __FUNCTION__);

    // Make sure that the location returned has the desired accuracy
    if (newLocation.horizontalAccuracy <= manager.desiredAccuracy)
        return;

    // Record the location information
    // ...
}

Under the hood, i think MKMapView also uses CLLocationManager to get user's current location? So, will this create any problems because i believe both CLLocationManager and MapView will try to use same location services? Will there be any conflicts and lack of accurate/required or current data?

A: 

See this SO entry: CLLocationManager uses the same data across all of its instances, so there is no conflict.

Laurent Etiemble
But if we set showUserLocation to TRUE and create a CLLocationManager in our custom class, we're essentially making two instances of CLLocationManager - one used by MKMapView and one in your custom class. Who'll get the location updates? The observer on userLocation.location or the didUpdateLocation: delegate method? If i start recording the locations in both of these, will the recorded locations be in sync?
Mustafa
Apparently, you can have multiple Location Managers and they'll give you accurate information. Although MapKit also uses CLLocationManager under the hood, creating a CLLocationManager and using it with MapKit won't create any conflicts.
Mustafa