Search code examples
swiftswiftuimapboxmglmapview

Dealing with multiple annotations at the same address in an MGLMapView using SwiftUI and Mapbox


The thing is, I can't find any documentation on this--does anyone know if there is a way to neatly deal with annotations in the same spot (either so that you can like click the annotation or a button to cycle through the annotations at that spot or something else)? I just need a way to cycle through the annotations in a specific spot and access them individually. Any help and/or suggestions would be greatly appreciated.

func mapView(_ mapView: MGLMapView, didSelect annotation: MGLAnnotation) {
    //I tried to do a check here for if selectedAnnotation == annotation { somehow cycle to the next annotation in that location } but I guess when you click an already selectedAnnotation, the didDeselect function is run or something
    selectedAnnotation = annotation
    mapView.setCenter(annotation.coordinate, zoomLevel: 17,  animated: true)
}

My annotation function looks like:

class AnnotationsVM: ObservableObject {
    @Published var annos = [MGLPointAnnotation]()
    @ObservedObject var VModel: ViewModel //= ViewModel()

    init(VModel: ViewModel) {
        self.VModel = VModel
        let annotation = MGLPointAnnotation()
        annotation.title = "Shoe Store"
        annotation.coordinate = CLLocationCoordinate2D(latitude: 40.78, longitude: -73.98)
        annotation.subtitle = "10:00AM - 11:30AM"
        annos.append(annotation)
    }

    func addNextAnnotation(address: String) {
        let newAnnotation = MGLPointAnnotation()
            self.VModel.fetchCoords(address: address) { lat, lon in
            if (lat != 0.0 && lon != 0.0) {
                newAnnotation.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lon)
            }

            newAnnotation.title = address
            newAnnotation.subtitle = "9:00PM - 1:00AM"
        

                if (lat != 0 && lon != 0) {
                    self.annos.append(newAnnotation)
                }
        }
    }
}

In my updateUIView function in the MapView (UIViewRepresentable) struct, I add the annos array to the map.


Solution

  • I ended up doing my own implementation--I made an array of annotations with the same latitude and longitude and then I added buttons to the custom callout to cycle through that array, keeping track of the annotation that I am looking at.