views:

1460

answers:

2

Is it possible to use the MKMapView's own location manager to return the users current location to pass into a webservice?

I have mapView.showsUserLocation=YES; and this does return a valid blue dot at my location, but in the simulator, its Cupertino - which is fine, but when i look at

mapView.userLocation.coordinate.latitude, its equal to 180, whereas a CLLocationManager returns the correct one, 37.3317.

I want to avoid having multiple location managers for my three tabs, so using the mapViews own would be helpful.

Thanks.

A: 

So, to use a unique CLLocateManager, you can create a class to be the delegate for all you maps., so, instead of doing:

self.locationManager = [[CLLocationManager alloc] init];
    _locationManager.delegate = self;

Do something like:

self.locationManager = [[CLLocationManager alloc] init];
    _locationManager.delegate = mySharedDelegate;

Where mySharedDelegate is your class with all the CLLocationManager delegate methods.

You can only get a valid coordinate for the userLocation, after the first calling of

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation

When this method is called it is because the GPS has found the new location and so the blue dot will be moved to there and the userLocation will have the new coordinate.

Use the following method on your CLLocationManager delegate to log the current location when it is found:

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"---------- locationManager didUpdateToLocation");
    location=newLocation.coordinate;

    NSLog(@"Location after calibration, user location (%f, %f)", _mapView.userLocation.coordinate.latitude, _mapView.userLocation.coordinate.longitude);
}

Have you got the idea?

Cheers,
VFN

vfn
Is it ok then, to have a separate location manager for each of my tabs and only share the delegate then? Or should i allocate and init one location manager in the app delegate and use that? thanks.
joec
+1  A: 

You can get the user location from the MKMapView. You are just missing a property in your retrieval of it. It should be:

mapView.userLocation.location.coordinate.latitude;

userLocation only stores a CLLocation location attribute and a BOOL updating attribute. You must go to the location attribute to get coordinates.

-Drew

Drew C