1 | initial version |
To create a custom map annotation using SwiftUI, follow these steps:
struct CustomAnnotationView: View {
var body: some View {
// Your custom annotation view code here
}
}
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
}
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()
}
}
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.