问题
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