iosswiftxcodemapkitmkpointannotation

How to turn a MKPointAnnotation to a button?


Whenever a user taps on an MKPointAnnotation, I want him to be redirected to a specific view. My problem is how do I get the annotation to perform an action when tapped?

Here is my code:

for i in closestpharmacyname {
                var docref2 = db.collection("pharmacies").document(i)
                print("Pharmacy: ", i)
                docref2.getDocument(source: .cache) { (document, error) in
                    if var document  = document {
                        var pharmacylatitude = document.get("latitude") as! Double
                        var pharmacylongitude = document.get("longitude") as! Double
                        print(pharmacylatitude, pharmacylongitude)
                             
                        var pharmacyannotation = MKPointAnnotation()
                        pharmacyannotation.coordinate = CLLocationCoordinate2D(latitude: pharmacylatitude, longitude: pharmacylongitude)
                        pharmacyannotation.title = i
                    
                        self.MapView.addAnnotation(pharmacyannotation)
                    } else{
                        print("Document Does not exist")
                    }
                    
                }
            }

Solution

  • To do this, you need to add:

    yourAnnotationView?.rightCalloutView = UIButton(type: UIButtonType.detailDisclosure)
    

    into your mapView(_:viewFor:) function. This will change the looks of your annotation, but there will be a button on the side that you can press to do different tasks.The annotation will look something like this:enter image description here

    In order to handle these tasks, you also need to add a new function:

    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
      //perform tasks here
    }