Why clusterAnnotationForMemberAnnotations in MKMapView is not called?

北城余情 提交于 2019-12-04 05:49:19

问题


I have a simple map view:

@IBOutlet private var mapView: MKMapView!

Then one by one I add annotations:

mapView.addAnnotation(Annotation(user: user))

and show them all:

mapView.showAnnotations(mapView.annotations, animated: true)

I also implemented the method:

func mapView(_ mapView: MKMapView, clusterAnnotationForMemberAnnotations memberAnnotations: [MKAnnotation]) -> MKClusterAnnotation {
    print(memberAnnotations)
    return MKClusterAnnotation(memberAnnotations: memberAnnotations)
}

but this is not called at all. Why?


回答1:


It appears as though it is required to set the clusteringIdentifier for the MKAnnotationView. This has worked for me:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier, for: annotation)
    annotationView.clusteringIdentifier = "identifier"
    return annotationView
}



回答2:


Check

class YourViewController: MKMapViewDelegate {

and

mapView.delegate = self

See also: https://github.com/artemnovichkov/iOS-11-by-Examples/blob/master/iOS-11-by-Examples/MapKit/MapKitViewController.swift




回答3:


@peter's answer worked for me, but I find it more intuitive to set the clusterIdentifier directly on your MKAnnotationView instead of using a delegate method to set it in. For example:

class VehicleAnnotationView: MKAnnotationView {
    override var annotation: MKAnnotation? {
        willSet {
            clusteringIdentifier = "1"

            canShowCallout = true
            calloutOffset = CGPoint(x: -5, y: 5)
            rightCalloutAccessoryView = UIButton(type: .detailDisclosure)

            image = UIImage(named: "MapVehiclePin")

        }
    }
}


来源:https://stackoverflow.com/questions/47914910/why-clusterannotationformemberannotations-in-mkmapview-is-not-called

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!