When multiple annotations are being displayed on a map, it is important to add some interaction to the annotations themselves. This is most simple if the annotations are MKMapItem objects, but if not, this can easily be achieved with tags.
To make it work you just need to provide a way for the Map view to know which of the annotations inside it is selected.
// Property to keep track of the selected annotation
@State var selectedTag: Int?
// Binding the property to the Map view
Map(selection: $selectedTag) {
Marker("Name", coordinate)
.tag(1)
}
The following view has a map with three markers on it:
Create a property called selectedTag that will be used to identify which annotation was selected by the user. Then let’s bind it to the Map view through its selection attribute.
Then make the annotations on the map identifiable with the .tag(:) modifier.
There is much more you can do with MapKit and SwiftUI. To see the latest updates on MapKit with SwiftUI check our article highlighting the updates made on WWDC in 2023.