Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To create a custom map annotation using SwiftUI, follow these steps:

  1. Create a new SwiftUI file for your annotation view.
struct CustomAnnotationView: View {
    var body: some View {
        // Your custom annotation view code here
    }
}
  1. Implement the MKMapViewDelegate protocol in your map view's SwiftUI struct.
struct MapView: UIViewRepresentable {

    // Properties and functions for your map view here

    // Implement the MKMapViewDelegate protocol
    class Coordinator: NSObject, MKMapViewDelegate {

        // Define your custom annotation view
        func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
            guard let annotation = annotation as? CustomAnnotation else { 
                return nil 
            }
            let identifier = "CustomAnnotation"
            var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
            if annotationView == nil {
                annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
                annotationView?.canShowCallout = false
            } else {
                annotationView?.annotation = annotation
            }
            annotationView?.image = UIImage(named: "custom-annotation-image")
            return annotationView
        }
    }

    func makeCoordinator() -> Coordinator {
        Coordinator()
    }

    // Other SwiftUI structs and functions for your map view implementation


}
  1. Define your custom annotation class.
class CustomAnnotation: NSObject, MKAnnotation {
    let title: String?
    let subtitle: String?
    let coordinate: CLLocationCoordinate2D

    init(
        title: String?,
        subtitle: String?,
        coordinate: CLLocationCoordinate2D
    ) {
        self.title = title
        self.subtitle = subtitle
        self.coordinate = coordinate
        super.init()
    }
}
  1. Add your custom annotation to the map view.
let customAnnotation = CustomAnnotation(title: "Custom annotation", subtitle: "Subtitle", coordinate: CLLocationCoordinate2D(latitude: 37.787358, longitude: -122.408227))
mapView.addAnnotation(customAnnotation)

And that's it! Your custom map annotation should now be displayed on the map view.