Let me preface this by saying I'm a complete newbie to Swift. I've been messing around with MapKit and am trying to add multiple annotations to a Map with different symbols representing each category of annotations.
To clarify, I have 2 arrays (list1 and list2). Both of these arrays contain Pin objects as defined below:
struct Pin: Identifiable{
let id = UUID()
let name: String
let coordinate: CLLocationCoordinate2D
}
I want to add locations from both list1 and list2 on the map as annotations, but use different SF symbols to indicate which list the point was sourced from.
So far, I am able to display points from just one of the lists.
struct MapView: View {
var body: some View {
ZStack(alignment: .top){
Map(coordinateRegion: $region, annotationItems: list1) {
MapAnnotation(coordinate: $0.coordinate){
Image(systemName: "house").foregroundColor(.blue)
}
}
To implement the different annotations I considered concatenating list1 and list2 but that wouldn't allow me to use different symbols for points from each list.
My end goal is to use toggle switches to show/hide annotations based on the state of the button.
How can I solve this? Thanks in advance.
CodePudding user response:
you could try this approach, where you concatenate list1 list2
, and test the item is contained in one of the list (list1):
Map(coordinateRegion: $region, annotationItems: list1 list2) { item in
MapAnnotation(coordinate: item.coordinate){
if list1.contains(where: {$0.id == item.id}) {
Image(systemName: "house").foregroundColor(.blue)// <-- here for list1
} else {
Image(systemName: "globe").foregroundColor(.red) // <-- here for list2
}
}
}