在 MapKit 中向地图添加注释的功能不起作用

问题描述

创建地图并向其添加注释的相关代码在这里

class LandmarkAnnotation: NSObject,MKAnnotation {
    let title: String?
    let subtitle: String?
    let coordinate: CLLocationCoordinate2D
init(title: String?,subtitle: String?,coordinate: CLLocationCoordinate2D) {
        self.title = title
        self.subtitle = subtitle
        self.coordinate = coordinate
    }
}


struct MapView: UIViewRepresentable {
    
    let landmarks = LandmarkAnnotation(title: "test",subtitle: "subtest",coordinate: CLLocationCoordinate2D(latitude: 37.786996,longitude: -122.419281))//.requestMockData()
    
    func makeCoordinator() -> MapViewCoordinator {
        MapViewCoordinator(self)
    }
    
    /**
     - Description - Replace the body with a make UIView(context:) method that creates and return an empty MKMapView
     */
    func makeUIView(context: Context) -> MKMapView{
        MKMapView(frame: .zero)
    }
    
    func updateUIView(_ view: MKMapView,context: Context){
        //If you changing the Map Annotation then you have to remove old Annotations
        //mapView.removeAnnotations(mapView.annotations)
        view.delegate = context.coordinator
        //This doesn't add annotations for some reason
        view.addAnnotations([landmarks])
        print(landmarks)
        //print returns <River_Watch.LandmarkAnnotation: 0x282758a80> for some reason
    }
}

/*
  Coordinator for using UIKit inside SwiftUI.
 */
class MapViewCoordinator: NSObject,MKMapViewDelegate {
    
      var mapViewController: MapView
        
      init(_ control: MapView) {
          self.mapViewController = control
      }
        
      func mapView(_ mapView: MKMapView,viewFor
           annotation: MKAnnotation) -> MKAnnotationView?{
         //Custom View for Annotation
          let annotationView = MKAnnotationView(annotation: annotation,reuseIdentifier: "customView")
          annotationView.canShowCallout = true
          //Your custom image icon
          annotationView.image = UIImage(named: "locationPin")
          return annotationView
       }
}

由于某种原因,变量“landmarks”的格式未正确添加为注释,当我打印该变量时,它返回了 <River_Watch.LandmarkAnnotation: 0x282758a80>,我认为这不是注释的正确格式。我哪里做错了?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)