Custom pin image in annotationView in iOS
The accepted answer doesn't work, as it has annotationView
uninitialized in else
block.
Here's a better solution. It dequeues annotation view if possible or creates a new one if not:
// https://stackoverflow.com/a/38159048/1321917
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
// Don't want to show a custom image if the annotation is the user's location.
guard !(annotation is MKUserLocation) else {
return nil
}
// Better to make this class property
let annotationIdentifier = "AnnotationIdentifier"
var annotationView: MKAnnotationView?
if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier) {
annotationView = dequeuedAnnotationView
annotationView?.annotation = annotation
}
else {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
annotationView?.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
}
if let annotationView = annotationView {
// Configure your annotation view here
annotationView.canShowCallout = true
annotationView.image = UIImage(named: "yourImage")
}
return annotationView
}
Here is the answer:
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
let identifier = "MyPin"
if annotation.isKindOfClass(MKUserLocation) {
return nil
}
let detailButton: UIButton = UIButton(type: UIButtonType.DetailDisclosure)
if let annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "pin")
annotationView.canShowCallout = true
annotationView.image = UIImage(named: "custom_pin.png")
annotationView.rightCalloutAccessoryView = detailButton
}
else {
annotationView.annotation = annotation
}
return annotationView
}
Regards