[英]Trouble while getting distance between two points
在我的iOS應用程序中,我要跟蹤從起點到我當前位置的距離。 我實現了這段代碼:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *currentLocation = [locations lastObject];
CLLocation *startLocation = [locations firstObject];
[coordArray addObject:currentLocation];
float speed = currentLocation.speed * 3.6;
if (speed > 0) {
self.labelSpeed.text = [NSString stringWithFormat:@"%.2f Km/h", speed];
[speedArray addObject:[NSNumber numberWithFloat:speed]];
}
CLLocationDistance distance = [startLocation distanceFromLocation:currentLocation];
}
但是,當我嘗試使用該應用程序時,它沒有得到距離。 我需要距離在標簽中顯示它並且距離我將使用以下等式計算步數:
steps = distance / length of human step
我知道它不准確,但我不能使用加速度計,因為它在iPhone顯示器不活動時不起作用。 一個人建議我這個解決方案 。 為什么我的代碼沒有給我一個距離?
回調
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
確實為您提供了至少一個位置,並且如果之前延遲了位置更新,則位置數組會保留多個對象。 要獲得步行/行駛距離,您必須將初始位置存儲在類變量或屬性中。 然后,當您想要計算距離時,請按照上面的代碼進行操作,但使用保存初始位置的類變量。
檢查以下代碼以獲取距離:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
if ([coordArray count]>0) {
CLLocation *currentLocation = manager.location;
CLLocation *startLocation = [coordArray objectAtIndex:0];
[coordArray addObject:currentLocation];
float speed = currentLocation.speed * 3.6;
if (speed > 0) {
NSLog(@"\n speed:%@",[NSString stringWithFormat:@"%.2f Km/h", speed]);
}
CLLocationDistance distance = [startLocation distanceFromLocation:currentLocation];
if (distance>0) {
NSLog(@"Distance:%@",[NSString stringWithFormat:@"%lf meters",distance]);
}
}
else{
[coordArray addObject:manager.location];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.