我尝试计算行进的总距离并将其输出到View Controller,但结果不符合预期。代码如下:
MyCLController.m
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
validLocation = YES;
if (!newLocation)
{
validLocation = NO;
}
if (newLocation.horizontalAccuracy < 0)
{
validLocation = NO;
}
// Filter out points that are out of order
NSTimeInterval secondsSinceLastPoint = -[newLocation.timestamp timeIntervalSinceNow];
if (secondsSinceLastPoint < 0)
{
validLocation = NO;
}
if (validLocation == YES)
{
[self.delegate locationChange:newLocation :oldLocation];
}
NewWorkoutViewController.m
-(void)locationChange:(CLLocation *)newLocation:(CLLocation *)oldLocation
{
CLLocationDistance meters = [newLocation distanceFromLocation:oldLocation];
currentSpeed = ([newLocation speed] * 3600) / 1000;
totalDistance = (totalDistance + meters) / 1000;
totalDistanceMeters = totalDistanceMeters + meters;
avgSpeed = totalDistance / counterInt;
[speedLbl1 setText:[NSString stringWithFormat:@"%.3f", currentSpeed]];
[distanceLbl1 setText:[NSString stringWithFormat:@"%.3f", totalDistance]];
}
问题在于我的totalDistance,它似乎每次都没有添加它,就像它覆盖它一样,当我在车上测试时我可以看到坐标之间10/20米的值,所以这个表示distanceFromLocation似乎正在工作。
有人有什么想法吗?
问候,斯蒂芬
答案 0 :(得分:2)
试试这个:
totalDistance = totalDistance + (meters / 1000);
而不是
totalDistance = (totalDistance + meters) / 1000;
你的方式,每次总距离除以1000,即如果你每次旅行10米:
totalDistance = (0+10) / 1000 = 0.01;
totalDistance = (0.01+10) / 1000 = 0.01001 //!< You expected this to be 0.02!
totalDistance = (0.01001+10) / 1000 = 0.01001001 //!< You expected this to be 0.03!