我有IBAction
:
-(IBAction)pressStart{
locationManager.delegate = self;
[locationManager startUpdatingLocation];
}
在
- (void)viewDidLoad
{
[super viewDidLoad];
duration.text = @"00:00:00";
speedLabel.text = @"00";
locationManager = [[CLLocationManager alloc]init];
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
}
这个方法:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
CLLocation *firstLocation = [locations objectAtIndex:0];
location = [locations lastObject];
CLLocationDistance meters = [location distanceFromLocation:firstLocation];
NSLog(@"meters= %f", meters);
而且我不知道为什么 firstLocation
会发生变化。也许有办法捕获 firstLocation?这应该是按下“开始”按钮时设备的位置。
最佳答案
您代码中的
firstLocation
不是位置更新开始后的第一个位置;这是自上次回调 locationManager:didUpdateLocations:
方法以来返回给您的第一个位置(在某些情况下,位置服务可能会在回调到您的委托(delegate)方法之前收集多个位置——最最近的位置始终是位置数组中的最后一个对象)。
如果您需要存储位置更新开始后的第一个位置,您应该创建一个属性,例如
@property (nonatomic, strong) CLLocation *startingLocation;
然后在locationManager:didUpdateLocations:
方法中,添加代码:
if (!self.startingLocation) {
self.startingLocation = [locations objectAtIndex:0];
}
这将在第一次回调后将起始位置存储到属性中。 (如果你想重置它,你可以将属性设置为 nil。)
不要忘记,您收到的第一个位置很多都不是很准确,因为如果最近没有启用定位服务,定位服务需要时间来确定设备的位置。
关于ios - 当一个改变用户位置而第二个应该保持不变时,如何计算位置之间的距离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21065450/