Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain user location from a MKMapView

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.

like image 799
joec Avatar asked Jan 13 '10 17:01

joec


2 Answers

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

EDIT: The MKMapView's userLocation does not update until the map has finished loading, and checking too early will return zeros. To avoid this, I suggest using the MKMapViewDelegate method -(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation.

like image 71
Drew C Avatar answered Oct 14 '22 03:10

Drew C


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

like image 20
vfn Avatar answered Oct 14 '22 02:10

vfn