从用户位置ios查找最近的注释?

我有一个注释数组。我正在计算每个注释与用户位置之间的距离。我想知道的是,如何从这些距离找到3个最接近的注释?

这是我如何计算从用户位置到注释的距离。

CLLocation *userLocation = self.mapView.userLocation.location; for (Annotation *obj in annotations) { CLLocation *loc = [[CLLocation alloc] initWithLatitude:obj.coordinate.latitude longitude:obj.coordinate.longitude]; // CLLocation *userLocation = [[CLLocation alloc] initWithLatitude:self.mapView.userLocation.coordinate.latitude longitude:self.mapView.userLocation.coordinate.longitude]; CLLocationDistance dist = [loc distanceFromLocation:userLocation]; int distance = dist; NSLog(@"Distance from Annotations - %i", distance); } 

userLocation是静态的,因此不要每次在循环中重新创建它。 您还可以直接获取位置:

 CLLocation *userLocation = self.mapView.userLocation.location; 

然后,您可以执行类似操作,将距离编号和注释存储到字典中,将距离作为键,将注释作为值。 构建字典后,对allKeys数组进行排序,然后您可以获得与前3个键相关联的注释。


假设您在运行此命令时始终至少有一个注释:

 CLLocation *userLocation = self.mapView.userLocation.location; NSMutableDictionary *distances = [NSMutableDictionary dictionary]; for (Annotation *obj in annotations) { CLLocation *loc = [[CLLocation alloc] initWithLatitude:obj.coordinate.latitude longitude:obj.coordinate.longitude]; CLLocationDistance distance = [loc distanceFromLocation:userLocation]; NSLog(@"Distance from Annotations - %f", distance); [distances setObject:obj forKey:@( distance )]; } NSArray *sortedKeys = [[distances allKeys] sortedArrayUsingSelector:@selector(compare:)]; NSArray *closestKeys = [sortedKeys subarrayWithRange:NSMakeRange(0, MIN(3, sortedKeys.count))]; NSArray *closestAnnotations = [distances objectsForKeys:closestKeys notFoundMarker:[NSNull null]]; 
 NSArray *numbers = [NSArray arrayWithObjects: [NSNumber numberWithInt:0], [NSNumber numberWithInt:3], [NSNumber numberWithInt:2], [NSNumber numberWithInt:8], nil]; NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES selector:@selector(localizedCompare:)]; NSArray *sortedNumbers = [numbers sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]]; 

你将所有距离存储在一个数组中并对其进行排序,然后在那里拾取数字

 [sortedNumbers objectAtIndex:0]; [sortedNumbers objectAtIndex:1]; [sortedNumbers objectAtIndex:2];