我正在研究这种行走/跑步应用程序,它以米为单位计算距离并记录纬度以供进一步使用。现在,当我计算距离时,每次都会得到不正确的距离。我将它与其他正在运行的应用程序进行了比较,它们通常显示的距离与我的距离不同。
以下是我正在使用的代码:
#define kDesiredAccuracy 5.0f
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
self.locationManager.distanceFilter = kDesiredAccuracy;
_routes = [[NSMutableArray alloc] init];
lastKnownLocation = nil;
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
// return if accuracy is less than 0 or is greater than desired accuracy.
if (newLocation.horizontalAccuracy < 0)
{
return;
}
if(newLocation.horizontalAccuracy > kDesiredAccuracy)
{
return;
}
NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
CLLocationSpeed speed = [newLocation speed];
// return if stale data or user is not moving
if (locationAge > 5.0 || speed <= 0) return;
//return if first location is found
if(lastKnownLocation == nil)
{
lastKnownLocation = newLocation;
return;
}
CLLocationDistance distance = [newLocation distanceFromLocation:(self.pramDistance > 0)?lastKnownLocation:oldLocation];
if(distance > 0)
{
// save distance for future use
NSMutableDictionary *dict=[[NSMutableDictionary alloc] init];
[dict setObject:[NSString stringWithFormat:@"%g", newLocation.coordinate.latitude] forKey:@"latitude"];
[dict setObject:[NSString stringWithFormat:@"%g", newLocation.coordinate.longitude] forKey:@"longtitude"];
[dict setObject:[NSString stringWithFormat:@"%f",distance] forKey:@"distance"];
[_routes addObject:dict];
// add distance to total distance.
self.pramDistance += distance;
}
}
一旦用户完成步行/跑步,我在地图视图上绘制步行/跑步的路线。为此,我只需使用所有记录的位置在MKMapView上绘制一条ploy线。
地图视图显示路线的Z字形线,距离始终不正确。请建议我在哪里做错了,我应该修改什么才能让它正常工作?
以下是比较(左边是其他应用,右边是我的):
答案 0 :(得分:1)
试试这个,
导入CLLocationManagerDelegate,
CLLocation *currentLocation = self.currentLocation;
float distanceMile = [currentLocation distanceFromLocation:[[CLLocation alloc] initWithLatitude:latitude longitude:longitude]]/1609.34;
-(void)postCurrentLocationOfDevice
{
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.distanceFilter = kCLDistanceFilterNone;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];
self.locationManager.delegate = self;
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
self.currentLocation = [locations objectAtIndex:0];
[self.locationManager stopUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
self.currentLocation = newLocation;
[self.locationManager stopUpdatingLocation];
}
答案 1 :(得分:1)
虽然我没有得到很多帮助,但我在这个问题上找到了一些帮助和想法:Corelocation incorrect distances
我为解决这个问题所做的是:
P.S。:我的代码很乱,命名约定不是通用的,这就是为什么我不在这里发布我的代码。