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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-06-18 11:00:00 +0000
Seen: 8 times
Last updated: Oct 23 '21
How to add a custom button in SwiftUI for iOS13 that enables going back between screens?
How can the update of properties from both ParentViewModel and ChildViewModel in SwiftUI be solved?
Can SwiftUI be utilized to restrict the touch region for a drag gesture?
How can the color of a selected element (Picker) be modified in SwiftUI for WatchOS?
How to make a calendar layout that is horizontal using Swiftui?
What is the process to add a radio button with a check mark on a TableView cell using Swift?
How to limit UITextField input to only accept numerical values?