CoreLocation负值

时间:2011-11-01 17:57:30

标签: iphone objective-c core-location

我正在使用CoreLocation框架来获取我的速度和距离来计算平均速度。

CoreLocation发出的第一次更新中,它显示速度和行进距离的负值。我该如何解决这个问题?

速度为locationController.locationManager.location.speed,其中locationController拥有我的CoreLocation代表。通过获取旧位置和新位置并计算距离来计算距离。

//Distance
- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
    // make sure the old and new coordinates are different
    if ((oldLocation.coordinate.latitude != newLocation.coordinate.latitude) &&
        (oldLocation.coordinate.longitude != newLocation.coordinate.longitude))
    {         
        mDistance = [newLocation distanceFromLocation:oldLocation];
    }
}

3 个答案:

答案 0 :(得分:5)

由于多种原因,Core Location返回的数据可能无效。在使用数据之前,请运行此方法以查看它是否有效。

// From http://troybrant.net/blog/2010/02/detecting-bad-corelocation-data/
- (BOOL)isValidLocation:(CLLocation *)newLocation
        withOldLocation:(CLLocation *)oldLocation 
{
    // filter out nil locations
    if (!newLocation){
        return NO;
    }
    // filter out points by invalid accuracy
    if (newLocation.horizontalAccuracy < 0){
        return NO;
    }
    // filter out points that are out of order
    NSTimeInterval secondsSinceLastPoint = [newLocation.timestamp 
                                            timeIntervalSinceDate:oldLocation.timestamp];
    if (secondsSinceLastPoint < 0){
        return NO;
    }
    // filter out points created before the manager was initialized
    NSTimeInterval secondsSinceManagerStarted = [newLocation.timestamp 
                                                 timeIntervalSinceDate:locationManagerStartDate];
    if (secondsSinceManagerStarted < 0){
        return NO;
    }
    // newLocation is good to use
    return YES;
} 

答案 1 :(得分:2)

CLLocationManager Class Reference中有一条注释:

  

由于返回初始位置可能需要几秒钟,因此位置管理员通常会立即提供先前缓存的位置数据,然后在可用时提供更多最新的位置数据。因此,在采取任何操作之前检查任何位置对象的时间戳总是一个好主意。

您应该检查是否获得了缓存值并忽略它,等待第一次“真正”更新。

NSTimeInterval timeSinceLastUpdate = [[newLocation timestamp] timeIntervalSinceNow];

// If the information is older than a minute, or two minutes, or whatever
// you want based on expected average speed and desired accuracy, 
// don't use it.
if( timeSinceLastUpdate < -60 ){
    return;
}

答案 2 :(得分:0)

如果您正在收集第一个点,则它没有参考计算速度或距离。我相信它被定义为返回-1,如果它无法满足你的需要。

要解决此问题,只需检查负值。

if(location.speed > 0) {
    return;
}