CLLocationManager always returns the exact same location

1.4k Views Asked by At

I am trying to set up a new CLLocation and CLRegion, but the location always returns with the same coordinates, regardless of where I actually am. My main UIViewController conforms to the CLLocationManagerDelegate protocol, as does a custom class. When the custom class initializes, I have a timer set to fire .25 seconds later, with this code:

mainLocationManager = [[CLLocationManager alloc] init];
[mainLocationManager startUpdatingLocation];
location = [mainLocationManager location];
if (![location.timestamp isEqualToDate:[NSDate dateWithTimeIntervalSinceNow:0]]) { //filters cached data by updating location if cached data not recent enough
    location = [mainLocationManager location];
}

//Set up region
region = [[CLRegion alloc] initCircularRegionWithCenter:location.coordinate
                                                     radius:500
                                                 identifier:[NSString stringWithFormat:@"region:%@", locationName]];
NSLog(@"%@       %@", location, region);

The code appears to work except that the coordinate is always the same value. I am not sure how to change this. Any help is appreciated, thanks!

3

There are 3 best solutions below

0
On BEST ANSWER

I think because you did not update location by location manager delegate method.

Get update location by this method

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

{
location_updated = [locations lastObject];    
NSLog(@"updated coordinate are %@",location_updated);

}

Also test it in device.

0
On

In order for this to work, you need to implement the delegate:

locationManager:didUpdateLocations:

see also here.

For correct usage:

How to get current location using CLLocationManager in iOS

0
On

The location manager is an asynchronous framework. You cant' call startUpdatingLocation and then immediately expect the location manager to have the user's correct location.

You have to set yourself as the location maanger's delegate, call startUpdatingLocation, and then wait for it to call your locationManager:didUpdateToLocation:fromLocation: method. In fact, you need to check the location updates that you get and reject old, stale location information or location updates that are too inaccurate (When you first turn on location updates the first update you get is from the last time the GPS was active, and is sometimes hours or days out of date. Then the next updates are quite inaccurate until the GPS settles down and starts giving good readings.)