【问题标题】:Adding annotations to MapKit in UIRepresentable在 UIRepresentable 中向 MapKit 添加注释
【发布时间】:2021-11-02 17:46:21
【问题描述】:

我正在使用 SwiftUI 并使用 MKMapView 在视图上显示地图、注释和叠加层。

我使用的是新的Map(),但由于缺乏覆盖支持,我又回到了 UIKit Representable。

当我使用Map 时,添加注释很容易,但是当使用UIKitRepresentable 时,我对将数据放在哪里以及如何从网络调用中提取的数组进行注释有点困惑。

我读过的所有内容要么是在 Obj-C 中,要么是添加了一个注释点。我正在尝试添加(目前约为 800 个),这就是为什么我想利用 MKMapView 的可重用性和集群性。

这是我目前拥有的:

struct UIMapView: UIViewRepresentable {
  
  @EnvironmentObject var dataModel: DataModel
  @EnvironmentObject var mapViewModel: MapViewModel

  func makeCoordinator() -> Coordinator { Coordinator() }
  
  func makeUIView(context: Context) -> MKMapView {
    let view = mapViewModel.mapView
    drawOverlayRing(view: view)
    view.delegate = context.coordinator
    return view
  }

  func updateUIView(_ uiView: MKMapView, context: Context) {}

  class Coordinator: NSObject, MKMapViewDelegate {
    func mapView(_ map: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
      if annotation is MKUserLocation { return nil }
      
      let identifier = "pinAnnotation"
      var annotationView = map.dequeueReusableAnnotationView(
        withIdentifier: identifier
      ) as? MKPinAnnotationView
      
      if annotationView == nil {
        annotationView = MKPinAnnotationView(
          annotation: annotation, 
          reuseIdentifier: identifier
        )
        annotationView?.canShowCallout = true
      } else {
        annotationView?.annotation = annotation
      }
      return annotationView
    }
  }

  func getAnnotations(view: MKMapView) {
    for location in dataModel.locations {
      let annotation = MKPointAnnotation()
      annotation.title = location.title
      annotation.coordinate = CLLocationCoordinate2D(
        latitude: location.latitude,
        longitude: location.longitude
      )
      view.addAnnotation(annotation)
    }
  }
}

【问题讨论】:

    标签: swift swiftui mapkit mapkitannotation


    【解决方案1】:

    我有时会将注释放在 updateUIView 中,如下所示:

    updateUIView() {
        // remove the old ones -->   uiView.removeAnnotations(uiView.annotations)
        uiView.addAnnotations(toMapAnnotations(locations: dataModel.locations))
    }
    
    func toMapAnnotations(locations: [CLLocationCoordinate2D]) -> [MapAnnotation] {
        return locations.map { MapAnnotation(location: $0) }
    }
    
    final class MapAnnotation: NSObject, MKAnnotation {...}  
    

    【讨论】:

      【解决方案2】:

      代码将在稍后提供,因为updateUIView 被多次调用。 我认为最好避免拨打addAnnotations

      【讨论】:

      • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-13
      • 1970-01-01
      • 2016-01-01
      相关资源
      最近更新 更多