开发者

CLLocationManager distanceFromLocation: returns -1

I am trying to use corelocation at the very beginning of my app, to get initial location.

I have delegate method:

-(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];
        }
    }
}

Here's the log output:

... -[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

Any idea why initial distance calculation from newlocation to oldlocation of (0,0) is yielding -1 result?


It seems like the distance is -1, because the old location (0,0) is invalid. I would ignore the first distance (-1) and wait for the next one.

To me it makes perfect sense that the first location can't have an old location.


Gosh, second time I'm answering my own question.. sorry I didn't debug enough i guess!

So here's what's happening - when delegate is called first time, it looks like oldLocation can be called with nil.

Thus, distanceFromLocation: is called with nil argument, and returning -1 as some sort of error code.

Anyway, I am now just adding a check to see if oldlocation is nil, and ignore that update for second one.

Would have been nice if distanceFromLocation: actually fires an assertion of some sort when called with nil argument, instead of cryptic -1 error code! :D

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜