测试已测试 | ✗ |
语言语言 | SwiftSwift |
许可 | MIT |
发布上次发布 | 2016年3月 |
SPM支持 SPM | ✗ |
由 freemiumdev 维护。
这是 FBAnnotationClustering 的 Swift 语言的移植版本。将地图上的标签聚合到单个编号的簇中。
地图聚类是现代应用程序中常见的地图功能。当我找不到 Swift 库时,我最终将一个 Objective-C 的库翻译成了 Swift。我选择的库是 FBAnnotationClustering(FB 代表 Filip Bec,而非 Facebook)。我希望得到一个快速(四叉树)的库,并且代码库轻量,以便将来如果我需要处理一些边缘情况的话。
(左:DC地区大量标签的示例项目。右:使用簇的 rible 截图)
将以下 Swift 文件复制到您的项目中
使用 FBViewController.swift 作为指导。作为一个演示,它将1000个随机的标签放置在加纳附近。
按照以下说明进行一个基本示例的实现。
let clusteringManager = FBClusteringManager()
var array:[FBAnnotation] = []
// drop two arbitrary pins somewhere near Louisville, Kentucky
let pinOne = FBAnnotation()
pinOne.coordinate = CLLocationCoordinate2D(latitude: 38.188805, longitude: -85.6767705)
let pinTwo = FBAnnotation()
pinTwo.coordinate = CLLocationCoordinate2D(latitude: 38.188806, longitude: -85.6767707)
array.append(pinOne)
array.append(pinTwo)
clusteringManager.addAnnotations(array)
将以下代码添加到 ViewController 的顶部
import MapKit
在 Storyboard 中添加一个 MapKit 视图,并设置代理。
添加以下 MKMapViewDelegate 方法
extension ViewController: MKMapViewDelegate {
func mapView(mapView: MKMapView!, regionDidChangeAnimated animated: Bool){
NSOperationQueue().addOperationWithBlock({
let mapBoundsWidth = Double(self.mapView.bounds.size.width)
let mapRectWidth:Double = self.mapView.visibleMapRect.size.width
let scale:Double = mapBoundsWidth / mapRectWidth
let annotationArray = self.clusteringManager.clusteredAnnotationsWithinMapRect(self.mapView.visibleMapRect, withZoomScale:scale)
self.clusteringManager.displayAnnotations(annotationArray, onMapView:self.mapView)
})
}
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
var reuseId = ""
if annotation.isKindOfClass(FBAnnotationCluster) {
reuseId = "Cluster"
var clusterView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
clusterView = FBAnnotationClusterView(annotation: annotation, reuseIdentifier: reuseId, options: nil)
return clusterView
} else {
reuseId = "Pin"
var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.pinColor = .Green
return pinView
}
}
}
对于图像的集群,您可以使用我提供的图像,或者您可以传递您项目中图像的名称。请记住,根据集群的大小,您可能需要3个不同的图像。
如果您要运行示例,在首次打开 Xcode 之前,请先在示例文件夹中打开终端,并运行以下命令:
pod install
之后,打开生成的 .xworkspace 文件。