swiftmapkitmkpointannotation

Swift, how can I store a custom value for each dropped pin using MKPointAnnotation?


I want to be able to store a custom value for each dropped pin using MKPointAnnotation. Specifically, I want to store some id with each pin and retrieve at calloutAccesoryControlTapped.


Solution

  • You'll have to subclass MKPointAnnotation with a property to store this custom value (I named it tag)

    import UIKit
    import MapKit
    class CustomPointAnnotation: MKPointAnnotation {
        var tag: Int!
    }
    

    Creating pins:

    let annotation = CustomPointAnnotation()
    annotation.coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(latitude), longitude: CLLocationDegrees(longitude))
                annotation.title = [insert name]
                annotation.tag = [insert tag]
                self.mapView.addAnnotation(annotation)
    

    And in your mapView delegate's viewForAnnotation, after checking the dequeableAnnotation you do:

      if (annotation is CustomPointAnnotation) {
           pinView?.tag = (annotation as! CustomPointAnnotation).tag
      }