iosswiftmapkitmapkitannotation

How can I show the annotation point information on the map?


When I click Annotation on the map, I want the information about the clicked location to appear in the back view at the bottom.I used Mapkit to create the map Image of the view I'm trying to make

Annotation Array

  let annotationLocations = [
        
        ["title":"X vet Clinic","latitude":39.895177 , "longitude":32.838194],
        ["title":"Y Vet Clinic","latitude": 39.894749, "longitude":32.841074],
        ["title":"Z Vet Clinic","latitude":  39.893615, "longitude":32.841476]
      
    ]

With this function, I can show the locations specified in the latitude longitudes above on the map

 func createAnnotations(locations: [[String: Any]])
    {
        
        for location in locations{
           let annotations = MKPointAnnotation()
            annotations.title = location["title"] as? String
         
            annotations.coordinate = CLLocationCoordinate2D(latitude: location["latitude"] as! CLLocationDegrees, longitude:  location["longitude"] as! CLLocationDegrees)
            myMap.addAnnotation(annotations)
            
        }
       
        
    }

Solution

  • You can subclass your annotation and put the required data in there;

    class VetClinicAnnotation: MKPointAnnotation {
        
        let name: String
        let address: String
        let image: UIImage
        
        init(with name: String, address: String, image: UIImage) {
            self.name = name
            self.address = address
            self.image = image
        }
        
    }
    

    Then you can get the annotation info from your map view delegate;

    func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
        
        if let annotation = view.annotation as? VetClinicAnnotation {
            // Use the annotation data
        }
        
    }