从用户位置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];
- 如何检查MKCoordinateRegion是否包含CLLocationCoordinate2D而不使用MKMapView?
- 仪器>分配不显示应用程序类/对象
- iOS UIActivityViewController使用UIActivityItemProvider“忘记”项目
- 想要在圈子中显示图像是可能的以及如何
- UISearchDisplayController的表视图的自定义类
- 在SWIFT中滚动时,我的表格视图将重用所选单元格
- 将PDFAnnotationSubtype等于.widget的PDFAnnotation在将其添加到PDFPage后不会刷新其外观
- 应用程序标题旁边的红点?
- Swift中的数字分组