Cluster,MKMapView显示许多时间相同的注释

时间:2018-04-27 12:50:52

标签: swift mkmapview mkannotation mkannotationview

所以,我有一个使用地图的快速应用程序(swift 3),在这个地图中我有很多注释,当用户更改地图区域时,它会更新。

我想使用pod“Cluster”,我添加它,当我放大显示群集中的内容时,注释几乎出现在同一个地方(有时它会形成一个圆圈,见图片)

enter image description here

我已经尝试过滤我的列表,只在集群中获取一次注释实例,但它不起作用。

每次用户更改区域时都会调用此方法:

   func createAnnotations(pois list:[PlaceModel]) {
    poiAnnotations.removeAll()

    let filteredAnnotations = mapView.annotations.filter { annotation in
        //if annotation is MKUserLocation { return false }          // don't remove MKUserLocation

        if let temp = annotation.subtitle, let value = temp {
            return value == "Place"
        }
        return false
    }

    clusterManager.remove(poiAnnotations)
    clusterManager.remove(filteredAnnotations)

    for poi in list {
        let centerLocation = CLLocation(latitude: mapView.centerCoordinate.latitude, longitude: mapView.centerCoordinate.longitude)
        if poi.getLocation().distance(from: centerLocation) > Double(Constants.POI_Radius) {
            continue
        }

        let annotation = Annotation()
        annotation.coordinate = CLLocationCoordinate2D(latitude: poi.latitude!, longitude: poi.longitude!)
        annotation.title = poi.name!
        annotation.subtitle = "Place"
        annotation.type =  .image( Images.MapPins.velhop)


        // For first value
        if poiAnnotations.isEmpty {
            poiAnnotations.append(annotation)
        }

        for pois in poiAnnotations {
            if poiAnnotations.contains(where: {$0.title == poi.name}) {
                // Do nothing
            } else {
                poiAnnotations.append(annotation)
            }
        }
    }    
    clusterManager.add(poiAnnotations)
}

这里是创建聚类和注释的地方:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if let annotation = annotation as? ClusterAnnotation {

        let identifier = "Cluster"
        var view = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)

        // Type for cluster
        let color = UIColor(red: 255/255, green: 149/255, blue: 0/255, alpha: 1)
        let type:ClusterAnnotationType = .color(color, radius: 25)

        if let view = view as? BorderedClusterAnnotationView {
            view.annotation = annotation
            view.configure(with: type)
        } else {
            view = BorderedClusterAnnotationView(annotation: annotation, reuseIdentifier: identifier, type: type, borderColor: .white)
        }
        return view
    } else {

        let identifier = "Pin"
        var view = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView

        if let view = view {
            view.annotation = annotation      
        } else {
            view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
        }

        return view
    }
}

我尝试了几件没有成功的事情。 提前谢谢。

0 个答案:

没有答案