Search code examples
swiftuiimageviewmapkitannotation

(Swift) Add a picture to my annotation callout


I need your help. I am working on an App which shows some locations near my user location. it shows the name of the place and the distance. What I am having trouble with is adding an image so the user can see the location description and a picture. How can I do it? My code is the following...

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

    let locationManager = CLLocationManager()

    struct Location {
    let title: String
    let latitude: Double
    let longitude: Double
    }


    let locations = [
    Location(title: "Saint Paul Hospital",     latitude: 49.280524700, longitude: -123.128232600)
    ]

    override func viewDidLoad() {
    super.viewDidLoad()

        mapita.showsUserLocation = true

        for location in locations {

        let annotation = MKPointAnnotation()
        annotation.title = location.title
        annotation.coordinate = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)


        if let currentLocation = locationManager.location?.coordinate {
            let locationMapPoint = MKMapPointForCoordinate(currentLocation)
            let pinMapPoint = MKMapPointForCoordinate(annotation.coordinate)


            let distance = MKMetersBetweenMapPoints(locationMapPoint, pinMapPoint)
            if distance >= 0 && distance <= 4500000 {
                let distancia: Double = round (distance / 1000)
                annotation.subtitle = "Dist. \(distancia) kilometros"
                mapita.addAnnotation(annotation)
            }
        }
    }

This is what I get. What I need is to put the image inside the callouts enter image description here

I would appreciate your help guys! Thank you


Solution

  • Try this:

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        if annotation is MKUserLocation { 
            return nil 
        }
    
        var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "pin")
    
        if annotationView == nil {
            annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "pin")
            annotationView!.canShowCallout = true
            annotationView!.image = UIImage(named: "sun")
        } else {
            annotationView!.annotation = annotation
        }
    
        return annotationView
    }