0

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

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 数组添加到地图中。

4

2 回答 2

1

更新上一个答案:

我(经常)误读了这个问题。因此,这是一个更新的存储库,它执行以下操作:

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

我把所有东西都推到了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())
  }
}

在此处输入图像描述

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


上一个答案,也许对某些人仍然有用。查看 repo 中的提交以获取代码。


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

该演示基于出色的MapBox 演示应用

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

我把所有东西都推到了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。查看上面的链接,了解它是如何通过协调器完成的

    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 Coordinator 中初始化 @EnvironmentObject 然后您可以将它用于包含所有 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 中设置 selectedText。这是 MapBox 委托与 SwiftUI 之间的连接。您也可以将注释放在@EnvironmentObject 中,我没有这样做,因为在演示应用程序中已经像这样定义了......

让我知道这是否有帮助。看看这个很开心...

在此处输入图像描述

于 2020-09-10T16:44:49.357 回答
0

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

于 2020-09-14T14:45:44.453 回答