FBAnnotationClustering 是一个 iOS 库,可以轻松高效地对地图通知进行聚类。查看关于它的博客文章。
创建你的聚类管理器(初始化时使用注释,或其他时间添加注释)
self.clusteringManager = [[FBClusteringManager alloc] initWithAnnotations:arrayOfAnnotations];
实现 MKMapView 的代理方法 mapView:regionDidChangeAnimated:
显示在地图上分组的注释。实现示例
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
[[NSOperationQueue new] addOperationWithBlock:^{
double scale = self.mapView.bounds.size.width / self.mapView.visibleMapRect.size.width;
NSArray *annotations = [self.clusteringManager clusteredAnnotationsWithinMapRect:mapView.visibleMapRect withZoomScale:scale];
[self.clusteringManager displayAnnotations:annotations onMapView:mapView];
}];
}
重要:每当你想自己刷新当前可见的地图矩形时(例如,如果你向 clusteringManager
添加了注释),请调用 mapView:regionDidChangeAnimated:
方法。
所有聚类都将具有 FBAnnotationCluster
类,因此在 MKMapView 的代理方法被调用时,你可以通过检查其实例来检查当前的注释是否是聚类。例如
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[FBAnnotationCluster class]]) {
FBAnnotationCluster *cluster = (FBAnnotationCluster *)annotation;
NSLog(@"Annotation is cluster. Number of annotations in cluster: %lu", (unsigned long)cluster.annotations.count);
} else {
NSLog(@"Normal annotation.")
}
...
}
要运行示例项目;克隆仓库,并首先从示例目录运行 pod install
。
如果你不喜欢 Cocapods,你可以将 FBAnnotationClustering 目录中的所有文件添加到你的项目中。
NSRecursiveLock
removeAnnotations:
方法
/**
Remove array of annotations from current annotation collection.
@param annotations Custom annotation objects.
*/
- (void)removeAnnotations:(NSArray *)annotations;
Filip Beć, [email protected]
由Infinum维护
FBAnnotationClustering 基于由 thoughtbot 编写的博客文章。
FBAnnotationClustering 可在 MIT 许可证下使用。有关详细信息,请参阅 LICENSE 文件。