当您第一次启动位置服务时,无论您是否在移动,通常都会看到多个位置更新。如果您检查位置的horizontalAccuracy,当它们进入时,您会看到,当它“预热”时,它将显示一系列位置的精度越来越高(即越来越小的horizontalAccuracy 值),直到它达到静止。
您可以忽略这些初始位置,直到 horizontalAccuracy 低于某个值。或者,更好的是,在启动期间,如果 (a) 新位置和旧位置之间的距离小于旧位置的 horizontalAccuracy 和 (b) 如果新位置的 horizontalAccuracy新位置小于之前的位置。
例如,假设您要维护一个 CLLocation 对象数组,以及对最后绘制路径的引用:
@property (nonatomic, strong) NSMutableArray *locations;
@property (nonatomic, weak) id<MKOverlay> pathOverlay;
此外,假设您的位置更新例程只是添加到位置数组,然后指示应该重绘路径:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
NSLog(@"%s", __FUNCTION__);
CLLocation* location = [locations lastObject];
[self.locations addObject:location];
[self addPathToMapView:self.mapView];
}
如果addPathToMapView 的准确度低于最后一个位置,并且它们之间的距离小于最近位置的准确度,那么addPathToMapView 可以移除最后一个位置的第二个位置。
- (void)addPathToMapView:(MKMapView *)mapView
{
NSInteger count = [self.locations count];
// let's see if we should remove the penultimate location
if (count > 2)
{
CLLocation *lastLocation = [self.locations lastObject];
CLLocation *previousLocation = self.locations[count - 2];
// if the very last location is more accurate than the previous one
// and if distance between the two of them is less than the accuracy,
// then remove that `previousLocation` (and update our count, appropriately)
if (lastLocation.horizontalAccuracy < previousLocation.horizontalAccuracy &&
[lastLocation distanceFromLocation:previousLocation] < lastLocation.horizontalAccuracy)
{
[self.locations removeObjectAtIndex:(count - 2)];
count--;
}
}
// now let's build our array of coordinates for our MKPolyline
CLLocationCoordinate2D coordinates[count];
NSInteger numberOfCoordinates = 0;
for (CLLocation *location in self.locations)
{
coordinates[numberOfCoordinates++] = location.coordinate;
}
// if there is a path to add to our map, do so
MKPolyline *polyLine = nil;
if (numberOfCoordinates > 1)
{
polyLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfCoordinates];
[mapView addOverlay:polyLine];
}
// if there was a previous path drawn, remove it
if (self.pathOverlay)
[mapView removeOverlay:self.pathOverlay];
// save the current path
self.pathOverlay = polyLine;
}
最重要的是,只需删除比您拥有的下一个位置更不准确的位置。如果你愿意,你可以在修剪过程中变得更加积极,但也有权衡,但希望这能说明这个想法。