使用 SwiftUI 和 Mapbox 处理 MGLMapView 中同一地址的多个注释

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

问题是,我找不到任何关于此的文档——有谁知道是否有一种方法可以巧妙地处理同一位置的注释(这样您就可以单击注释或按钮循环浏览该点或其他地方的注释)?我只需要一种方法来循环浏览特定位置的注释并单独访问它们。任何帮助 and/or 的建议将不胜感激。

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)
}

我的注释函数如下所示:

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)
                }
        }
    }
}

在 MapView (UIViewRepresentable) 结构中的 updateUIView 函数中,我将 annos 数组添加到地图中。

更新上一个答案:

我(一如既往)误读了这个问题。 所以这是一个更新的回购协议,它执行以下操作:

您可以根据需要将任意多个位置添加到同一地点(地点 A 和地点 B)。当您 select 一个地点时,自定义视图将打开并显示更多信息。然后,您可以遍历位于同一地点的所有位置。这是通过比较初始 selected 点的纬度和经度来完成的。

我把所有东西都推到了github

我尽量保持简短: 在模型中,我从同一地点获取所有位置,计算它并为视图设置它。

import SwiftUI
import Combine
import Mapbox

struct AnnotationLocation{
  let latitude: Double
  let longitude: Double
  let title: String?
}

/// Source of Truth
class AnnotationModel: ObservableObject {
  var didChange = PassthroughSubject<Void, Never>()
  
  var annotationsForOperations: [AnnotationLocation] =  [AnnotationLocation]()
  @Published var locationsAtSameSpot: [AnnotationLocation] =  [AnnotationLocation]()
  @Published var showCustomCallout: Bool = false
  @Published var countSameSpots: Int = 0
  @Published var selectedAnnotation: AnnotationLocation = AnnotationLocation(latitude: 0, longitude: 0, title: nil)
  
  func addLocationInModel(annotation: MGLPointAnnotation) {
    
    let newSpot = AnnotationLocation(latitude: annotation.coordinate.latitude, longitude: annotation.coordinate.longitude, title: annotation.title ?? "No Title")
    annotationsForOperations.append(newSpot)
  }
  
  func getAllLocationsFormSameSpot() {
    locationsAtSameSpot = [AnnotationLocation]()
    
    for annotation in annotationsForOperations {
      if annotation.latitude == selectedAnnotation.latitude &&
        annotation.longitude == selectedAnnotation.longitude {
        locationsAtSameSpot.append(annotation)
      }
    }
  }
  
  func getNextAnnotation(index: Int) -> Bool {
    if locationsAtSameSpot.indices.contains(index + 1) {
      selectedAnnotation = locationsAtSameSpot[index + 1]
      return true
    } else {
      return false
    }
  }
}

MapView 委托设置初始位置并触发模型中的函数以从同一地点获取所有位置。

func mapView(_ mapView: MGLMapView, didSelect annotation: MGLAnnotation) {
      
      /// Create a customLoaction and assign it the model
      /// The values are needed to loop though the same annotations
      let customAnnotation = AnnotationLocation(latitude: annotation.coordinate.latitude, longitude: annotation.coordinate.longitude, title: annotation.title ?? "No Tilte")
      
      /// assignselected annotion  @EnvironmentObject
      /// so it can be shown in the custom callout
      annotationModel.selectedAnnotation = customAnnotation
      
      /// show custom call out
      annotationModel.showCustomCallout = true
      
      /// count locations at same spot
      /// also pushes same locations into separte array to loop through
      annotationModel.getAllLocationsFormSameSpot()
      
      mapView.setCenter(annotation.coordinate, zoomLevel: 17,  animated: true)
    }

最后是 SwiftUI 视图,应该是自我解释...

import SwiftUI
import Mapbox

struct ContentView: View {
  @EnvironmentObject var annotationModel: AnnotationModel
  
  @State var annotations: [MGLPointAnnotation] = [MGLPointAnnotation]()
  @State private var showAnnotation: Bool = false
  @State private var nextAnnotation: Int = 0
  
  var body: some View {
    GeometryReader{ g in
      VStack{
        ZStack(alignment: .top){
          MapView(annotations: self.$annotations).centerCoordinate(.init(latitude: 37.791293, longitude: -122.396324)).zoomLevel(16).environmentObject(self.annotationModel)
          
          if self.annotationModel.showCustomCallout {
            VStack{
              
              HStack{
                Spacer()
                Button(action: {
                  self.annotationModel.showCustomCallout = false
                }) {
                  Image(systemName: "xmark")
                    .foregroundColor(Color.black)
                    .font(Font.system(size: 12, weight: .regular))
                }.offset(x: -5, y: 5)
                
              }
              
              HStack{
                Text("Custom Callout")
                  .font(Font.system(size: 12, weight: .regular))
                  .foregroundColor(Color.black)
              }
              
              Spacer()
              
              Text("Selected: \(self.annotationModel.selectedAnnotation.title ?? "No Tiltle")")
                .font(Font.system(size: 16, weight: .regular))
                .foregroundColor(Color.black)
                
              Text("Count same Spot: \(self.annotationModel.locationsAtSameSpot.count) ")
                .font(Font.system(size: 16, weight: .regular))
                .foregroundColor(Color.black)
              
               Spacer()
              
              Button(action: {
                let gotNextSpot = self.annotationModel.getNextAnnotation(index: self.nextAnnotation)
                if gotNextSpot {
                  self.nextAnnotation += 1
                } else {
                  self.nextAnnotation = -1 // a bit dirty...
                }
                
              }) {
                Text("Get Next Spot >")
              }
              
            }.background(Color.white)
              .frame(width: 200, height: 250, alignment: .center)
              .cornerRadius(10)
              .offset(x: 0, y: 0)
          }
        }
        
        VStack{
          HStack{
          Button(action: {
            self.addNextAnnotation(address: "Spot \(Int.random(in: 1..<1000))", isSpotA: true)
          }) {
            Text("Add to Spot A")
          }.frame(width: 200, height: 50)
          
         Button(action: {
          self.addNextAnnotation(address: "Spot \(Int.random(in: 1..<1000))", isSpotA: false)
         }) {
           Text("Add to Spot B")
         }.frame(width: 200, height: 50)
        }
           Spacer().frame(height: 50)
        }
      }
    }
  }
  
  /// add a random annotion to the map
  /// - Parameter address: address description
  func addNextAnnotation(address: String, isSpotA: Bool) {
    
    var newAnnotation = MGLPointAnnotation(title: address, coordinate: .init(latitude:  37.7912434, longitude: -122.396267))
    
    if !isSpotA {
      newAnnotation = MGLPointAnnotation(title: address, coordinate: .init(latitude:  37.7914434, longitude: -122.396467))
    }
    
    
    /// append to @State var which is used in teh mapview
    annotations.append(newAnnotation)
    
    /// also add location to model for calculations
    /// would need refactoring since this is redundant
    /// i leave it like that since it is more a prove of concept
    annotationModel.addLocationInModel(annotation: newAnnotation)
  
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView().environmentObject(AnnotationModel())
  }
}

边缘仍然很粗糙,但可能是一个起点。


上一个答案,可能对某些人仍然有用。 查看回购中的提交以获取代码..


这是一个 MapBox 视图的工作演示,用于添加随机注释,当您 select 其中一个注释时,它会循环遍历注释数组并在 TextView 中显示 selected 注释:

此演示基于优秀的 MapBox demo app

为了添加所需的功能,我决定为模型使用@EnvironmentObject。这很有帮助

我把所有东西都推到了github 我没有使用您的模型,但我认为您可以将您的功能集成到 AnnotationModel 中,或者也可以在 SwiftUI 视图中执行逻辑。

这是我所做的:

  1. 定义模型:

    import SwiftUI
    import Combine
    
    /// Source of Truth
    class AnnotationModel: ObservableObject {
     var didChange = PassthroughSubject<Void, Never>()
     @Published var selectedAnnotaion: String = "none"
    }
    
  2. 将@EnvironmentObject 添加到 SceneDelegate

     let contentView = ContentView().environmentObject(AnnotationModel())
    
  3. 棘手的部分是使用 MapBox UIViewRepresentable 将它连接到 @EnvironmentObject。查看上面的 link,了解它是如何通过 Coordinator

    完成的
    struct MapView: UIViewRepresentable {
        @Binding var annotations: [MGLPointAnnotation]
        @EnvironmentObject var annotationModel: AnnotationModel
    
        let mapView: MGLMapView = MGLMapView(frame: .zero, styleURL: MGLStyle.streetsStyleURL)
    
        // MARK: - Configuring UIViewRepresentable protocol
    
        func makeUIView(context: UIViewRepresentableContext<MapView>) -> MGLMapView {
          mapView.delegate = context.coordinator
          return mapView
        }
    
        func updateUIView(_ uiView: MGLMapView, context:      UIViewRepresentableContext<MapView>) {
          updateAnnotations()
        }
    
        func makeCoordinator() -> MapView.Coordinator {
          Coordinator(self, annotationModel: _annotationModel)
        }
    
  4. 在 MapBox 协调器中初始化 @EnvironmentObject 然后你可以使用它 Class 包含所有 MapBox 代表。在 didSelect 委托中,我可以循环遍历 MapView 中 @Binding 的注释,并通过 SwiftUI 中的 @State var 进一步设置。

    final class Coordinator: NSObject, MGLMapViewDelegate {
         var control: MapView
        @EnvironmentObject var annotationModel: AnnotationModel
    
    init(_ control: MapView, annotationModel: EnvironmentObject<AnnotationModel>) {
      self.control = control
      self._annotationModel = annotationModel
    }
    
    func mapView(_ mapView: MGLMapView, didSelect annotation: MGLAnnotation) {
     guard let annotationCollection = mapView.annotations else { return }
    
     /// cycle throu the annotations from the binding
     /// @Binding var annotations: [MGLPointAnnotation]
     for _annotation in annotationCollection {
       print("annotation", annotation)
    
    if annotation.coordinate.latitude == _annotation.coordinate.latitude {
      /// this is the same annotation
      print("*** Selected annoation")
      if let hastTitle = annotation.title {
        annotationModel.selectedAnnotaion = hastTitle ?? "no string in title"
      }
    } else {
      print("--- Not the selected annoation")
    }
    }
    
  5. 最后是 SwiftUI 视图

     import SwiftUI
     import Mapbox
    
     struct ContentView: View {
       @EnvironmentObject var annotationModel: AnnotationModel
    
       @State var annotations: [MGLPointAnnotation] = [
         MGLPointAnnotation(title: "Mapbox", coordinate: .init(latitude: 37.791434, longitude: -122.396267))
       ]
    
       @State private var selectedAnnotaion: String = ""
    
       var body: some View {
    VStack{
      MapView(annotations: $annotations).centerCoordinate(.init(latitude: 37.791293, longitude: -122.396324)).zoomLevel(16).environmentObject(annotationModel)
    
      VStack{
        Button(action: {
          self.addNextAnnotation(address: "Location: \(Int.random(in: 1..<1000))")
        }) {
          Text("Add Location")
        }.frame(width: 200, height: 50)
    
        Text("Selected: \(annotationModel.selectedAnnotaion)")
    
        Spacer().frame(height: 50)
      }
    }
       }
    
       /// add a random annotion to the map
       /// - Parameter address: address description
       func addNextAnnotation(address: String) {
         let randomLatitude = Double.random(in: 37.7912434..<37.7918434)
         let randomLongitude = Double.random(in: 122.396267..<122.396867) * -1
         let newAnnotation = MGLPointAnnotation(title: address, coordinate: .init(latitude: randomLatitude, longitude: randomLongitude))
    
         annotations.append(newAnnotation)
       }
     }
    
     struct ContentView_Previews: PreviewProvider {
       static var previews: some View {
         ContentView().environmentObject(AnnotationModel())
       }
     }
    

重要的是要知道 @State var 在 MapBox 中设置注释。 MapBox 委托循环遍历此数组并设置 @EnvironmentObject.This 中的 selectedText 是 MapBox 委托返回 SwiftUI 之间的连接。您也可以将注释放在@EnvironmentObject 中,我没有这样做,因为在演示应用程序中已经像那样定义了...

如果有帮助请告诉我。很高兴检查这个...

我最终完成了自己的实现——我制作了一组具有相同纬度和经度的注释,然后我将按钮添加到自定义标注以循环浏览该数组,跟踪我正在查看的注释在