CLLocationManager didUpdateToLocation检查失败

时间:2011-08-08 10:09:17

标签: iphone objective-c xcode cllocationmanager

我正在尝试使用CLLocationManager获取位置坐标。这是我的代码

- (void)viewDidLoad {
    [super viewDidLoad];

    //instantiate location manager and set delegate
    self.locationManager=[[CLLocationManager alloc]init];
    locationManager.delegate=self;
    // can be set to 100m,1km,3km etc.
    //locationManager.distanceFilter=10.0f;
    locationManager.desiredAccuracy=kCLLocationAccuracyNearestTenMeters;
    //start updating the delegate
    [locationManager startUpdatingLocation];
}

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

    // Check if the coordinates are different from the old ones
    if (newLocation.coordinate.latitude != oldLocation.coordinate.latitude && 
        newLocation.coordinate.longitude != oldLocation.coordinate.longitude) {     

        NSLog(@"not equal");        
    } else {
        NSLog(@"equal");
    }
}

但是我发现这个条件被调用了两次。第一次满足条件并打印不等于并立即再次调用并打印“相等”。 some1可以帮助我吗?我做错了什么?

由于

1 个答案:

答案 0 :(得分:2)

这是因为CoreLocation缓存了您的上一个位置并在您调用 startUpdatingLocation 后立即返回它,因此您必须验证坐标时间戳并且它太旧,您可以忽略旧坐标。

<强>更新

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    if([newLocation horizontalAccuracy] < 0.0f) return;
    if(fabs([[newLocation timestamp] timeIntervalSinceNow]) > kCLLocationMaximumLocationDataAge) return;
    if(fabs([[oldLocation timestamp] timeIntervalSinceNow]) < kCLLocationMaximumLocationDataAge && [newLocation getDistanceFrom:oldLocation] < 0.1f && [newLocation horizontalAccuracy] == [oldLocation horizontalAccuracy])
        return;
    if(((runningHighPreciseLocationDetectionService||runningLowPowerLocationDetectionService) && ([newLocation horizontalAccuracy] <= kCLLocationAccuracyHundredMeters))){
        NSLog(@"---> \n%@\n%@\nHorizontal accurecy: %f\nLocation age: %fs\nOld location age: %fs", NSStringFromSelector(_cmd), newLocation, newLocation.horizontalAccuracy, fabs([[newLocation timestamp] timeIntervalSinceNow]), fabs([[oldLocation timestamp] timeIntervalSinceNow]));
    } else {
        NSLog(@"\n-------------- BAD ---------------\n%@\n%@\nHorizontal accurecy: %f\nLocation age: %fs\nOld location age: %fs\n----------------------------------", NSStringFromSelector(_cmd), newLocation, newLocation.horizontalAccuracy, fabs([[newLocation timestamp] timeIntervalSinceNow]), fabs([[oldLocation timestamp] timeIntervalSinceNow]));
    }
    if(((runningHighPreciseLocationDetectionService||runningLowPowerLocationDetectionService) && ([newLocation horizontalAccuracy] <= kCLLocationAccuracyHundredMeters))){
        [self stopLocationImprovementTimer];
    } else [self createLocatinoImprovementTimer];
}
用于启动计时器的

createLocatinoImprovementTimer 方法,该计时器将工作一段时间,如果没有停止,它将发送和更新位置的通知,这是最后一次。在通知控制器之前,此计时器将有助于以更高的准确度等待坐标。