CLLocationManager distanceFromLocation:返回-1

时间:2011-03-12 12:36:32

标签: iphone distance cllocationmanager

我正在尝试在我的应用程序的最开始使用corelocation,以获取初始位置。

我有委托方法:

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

    NSDate* eventDate = newLocation.timestamp;
    NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];

    DLog(@"received location data from %f ago, lat/long - %+.6f, %+.6f\nold lat/long %+.6f, %+.6f\nhorizontal accuracy is %f", 
     howRecent, newLocation.coordinate.latitude, newLocation.coordinate.longitude, 
     oldLocation.coordinate.latitude, oldLocation.coordinate.longitude, 
     newLocation.horizontalAccuracy);

    // check if new update is significantly different from old one.  If it is, then reverse-geocode.
    if ([newLocation respondsToSelector:@selector(distanceFromLocation:)]) {
        DLog(@"distance from old to new location - %f", [newLocation distanceFromLocation:oldLocation]);
        if ([newLocation distanceFromLocation:oldLocation] < 1000) {
            // reverse geocode please
            [self stopLocationManager];
        }
    }

    else if ([newLocation respondsToSelector:@selector(getDistanceFrom:)]){
        DLog(@"distance from old to new location - %f", [newLocation getDistanceFrom:oldLocation]);
        if ([newLocation getDistanceFrom:oldLocation] < 1000) {
            // reverse geocode please
            [self stopLocationManager];
        }
    }
}

这是日志输出:

... -[AppHelper locationManager:didUpdateToLocation:fromLocation:] received location data from -13.261873 ago, lat/long - +37.705413, -121.866296
old lat/long +0.000000, +0.000000
horizontal accuracy is 1982.000000
... -[AppHelper locationManager:didUpdateToLocation:fromLocation:] distance from old to new location - -1.000000

知道为什么从newlocation到oldlocation(0,0)的初始距离计算产生-1结果?

2 个答案:

答案 0 :(得分:2)

似乎距离为-1,因为旧位置(0,0)无效。我会忽略第一个距离(-1)并等待下一个距离。

对我而言,第一个位置不能有旧位置是完全合理的。

答案 1 :(得分:0)

天哪,我第二次回答自己的问题..抱歉,我猜不够调试!

所以这就是正在发生的事情 - 当第一次调用委托时,看起来可以用nil调用oldLocation。

因此,distanceFromLocation:使用nil参数调用,并返回-1作为某种错误代码。

无论如何,我现在只是添加一个检查以查看oldlocation是否为nil,并忽略第二个更新。

如果distanceFromLocation:在使用nil参数调用时实际触发某种断言,而不是隐藏的-1错误代码,那会不错! :d