0

I'm using Swift 3 and Xcode 10 beta 3 and I need to use a custom image for my pins on the map. After the help of a guy on another post we made this code, it's all working except the pins are still the default.

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        if let annotation = annotation as? Annotation {
            let identifier = "identifier"
            let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
            annotationView.image = annotation.image //add this
            annotationView.canShowCallout = true
            annotationView.calloutOffset = CGPoint(x: -5, y: 5)
            annotationView.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) as UIView
            return annotationView
        }
        return nil
    }

    let marker = Annotation(title: "LVR" , subtitle: "" , coordinate: CLLocationCoordinate2D(latitude: 43.772523, longitude: 11.254356))
    marker.image = UIImage(named: "antonioli.png")
    //mapView.addAnnotation(marker)
    self.map.addAnnotation(marker)

The PNG file is in the main folder of my project like this: Description

How should I handle this problem?

traiantomescu
  • 65
  • 3
  • 12
  • Refer this : https://stackoverflow.com/questions/29116571/change-pin-image-on-mkmapview-in-swift – Kuldeep Jul 09 '18 at 10:47

1 Answers1

0

Here MyAnnotation is a subclass of NSObject, MKAnnotation

func mapView(_ mapView: MKMapView,viewFor annotation: MKAnnotation) -> MKAnnotationView?
{
    if annotation is MyAnnotation == false
    {

        return nil
    }

    let senderAnnotation = annotation as! MyAnnotation

    let pinReusableIdentifier = senderAnnotation.pinColor.rawValue

    var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: pinReusableIdentifier)

    if annotationView == nil
    {
        annotationView = MKAnnotationView(annotation: senderAnnotation,                                                                                                reuseIdentifier: pinReusableIdentifier)
        annotationView!.canShowCallout = true

    }
    let pinImage = UIImage(named:"location_curr.png")

    annotationView!.image = pinImage

    return annotationView

}

See Demo MapCustomImage

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87