Joe Sloan Joe Sloan - 4 months ago 21
Swift Question

Associating different pin images with different locations iOS

I have an array of 4 locations, and an array of 4 pin names (ie "bluePin.png | redPin.png | etc...")

Currently I'm using a bit of code I found elsewhere to add custom pin graphics to all 4 locations, but all of my pins are red.

func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
let annotationReuseId = "Truck"
var trkPin = mapView.dequeueReusableAnnotationViewWithIdentifier(annotationReuseId)
if trkPin == nil {
trkPin = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationReuseId)
} else {
trkPin!.annotation = annotation
}
trkPin!.image = UIImage(named: "redPin.png")
trkPin!.backgroundColor = UIColor.clearColor()
trkPin!.canShowCallout = false
return trkPin
}


How could I associate the pin colors with the locations in the array, so that each location is differentiated by color?

Thanks!

Answer

I have done this in the simple way by declaring array of location and array images. And I have viewDidLoad method as follows.

 override func viewDidLoad() {
    super.viewDidLoad()
    self.mapView.delegate = self

    let location = [
        CLLocationCoordinate2D(latitude: 12, longitude: 77),
        CLLocationCoordinate2D(latitude: 12.5, longitude: 77.5),
        CLLocationCoordinate2D(latitude: 13, longitude: 78),
        CLLocationCoordinate2D(latitude: 13.5, longitude: 78)
    ]

    let pins = [
        "red.png",
        "blue.png",
        "green.png",
        "yellow.png"
    ]

    var annotations = [MKPointAnnotation]()
    for (index, eachLocation) in location.enumerate() {
        let pinImageName = pins[index]
        let annotation = MKPointAnnotation()
        annotation.coordinate = eachLocation
        annotation.title = "\(pinImageName)"
        annotations.append(annotation)
    }
    mapView.addAnnotations(annotations)
}

And in the viewForAnnotation delegate method just getting that image name from the title property and explicitly disabling the callout

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
    let annotationReuseId = "Truck"
    var trkPin = mapView.dequeueReusableAnnotationViewWithIdentifier(annotationReuseId)
    if trkPin == nil {
        trkPin = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationReuseId)
        trkPin!.canShowCallout = false
    } else {
        trkPin!.annotation = annotation
        if let image = annotation.title {
            trkPin!.image = UIImage(named: image ?? "default.png")
        } else {
            trkPin!.image = UIImage(named: "default.png")
        }
    }
    return trkPin
}