- 过滤掉缓存的 (旧的) 位置数据,
- 过滤掉无效的位置结果 (精度 < 0),
- 将精度要求设置为
kCLLocationAccuracyBest
,
- 设置最小距离过滤器,最好至少为10米以过滤掉位置噪声。
- 编辑:当
oldLocation
为空时,不要计算距离。
你还可以做更多的工作,但如果你能得到足够好的水平精度(<30m),这应该就可以了。你可以过滤掉低精度的结果,但这样你就必须自己跟踪oldLocation
,这有点复杂。
添加一个NSLog (见下文) ,这样你就可以找出发生了什么。 如果你仍然不能得到好的结果,请发布NSLog的输出,这样我们就可以看到发生了什么并提供更多的帮助。
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSTimeInterval age = -[newLocation.timestamp timeIntervalSinceNow];
if (age > 120) return;
if (newLocation.horizontalAccuracy < 0) return;
if (oldLocation == nil || oldLocation.horizontalAccuracy < 0) return;
CLLocationDistance distance = [newLocation distanceFromLocation: oldLocation];
NSLog(@"%6.6f/%6.6f to %6.6f/%6.6f for %2.0fm, accuracy +/-%2.0fm",
oldLocation.coordinate.latitude,
oldLocation.coordinate.longitude,
newLocation.coordinate.latitude,
newLocation.coordinate.longitude,
distance,
newLocation.horizontalAccuracy);
distanceMoved += distance;
theLabel.text = [NSString stringWithFormat: @"%f meters", distanceMoved];
}
- (void)viewDidLoad
{
locMan = [[CLLocationManager alloc] init];
locMan.delegate = self;
locMan.desiredAccuracy = kCLLocationAccuracyBest;
locMan.distanceFilter = 10;
[locMan startUpdatingLocation];
isInitial = true;
distanceMoved = 0.0;
[super viewDidLoad];
}
iOS6更新如果您希望使用didUpdateLocations:来完成相同的操作(因为上述方法已经过时),最简单的解决方案是在类中声明一个属性来保存每个位置,以便在下一次更新时可以得到前一个位置。 声明一个属性来保存oldLocation
:
@property (nonatomic, retain) CLLocation* oldLocation;
然后在委托方法中,您可以保存每个newLocation
,以便在下次调用委托方法时将其用作oldLocation
:
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocations:(NSArray *)locations
{
CLLocation* newLocation = [locations lastObject];
NSTimeInterval age = -[newLocation.timestamp timeIntervalSinceNow];
if (age > 120) return;
if (newLocation.horizontalAccuracy < 0) return;
if (self.oldLocation == nil || self.oldLocation.horizontalAccuracy < 0) {
self.oldLocation = newLocation;
return;
}
CLLocationDistance distance = [newLocation distanceFromLocation: self.oldLocation];
NSLog(@"%6.6f/%6.6f to %6.6f/%6.6f for %2.0fm, accuracy +/-%2.0fm",
self.oldLocation.coordinate.latitude,
self.oldLocation.coordinate.longitude,
newLocation.coordinate.latitude,
newLocation.coordinate.longitude,
distance,
newLocation.horizontalAccuracy);
distanceMoved += distance;
theLabel.text = [NSString stringWithFormat: @"%f meters", distanceMoved];
self.oldLocation = newLocation;
}
didUpdateToLocation
方法已经改变。由于它只有一个NSArray
位置参数,我们该如何实现它?我正在尝试实现相同的功能。 - rohan-patelself.oldLocation
?我昨天就卡在那了。locations
数组只包含最新的位置.. :/ - rohan-patel