首页 > 解决方案 > 引脚未显示在 mapView 中。斯威夫特 5

问题描述

我需要在地图上显示图钉(注释)。然后从引脚到引脚绘制多边形线(注释到注释)

我收到一个转换为 CLLocationCoordiante2D 的 Doubles 数组。第一个 lat 和 long 值始终为 0.0,所以我从数组中删除它们,因为我不希望出现任何问题。

我将双打映射到坐标,并将它们添加到 mapView

我还包含了一个 viewFor 函数,我认为我真的不需要?

地图不会缩放到任何位置,也不会显示任何图钉。我知道我需要把它编码进去,我想要一个围绕所有引脚的一般半径。在别针实际出现后,我会继续努力。

另外,我不在乎名字,我只想让别针出现。

我试过设置一个坐标,但仍然没有别针。

mapView 委托在 viewDidLoad() 中正确设置

我在调试器中记录位置,它们显示正确。

func createAnnotations() {
    latitude.remove(at: 0)
    longitude.remove(at: 0)

   let coordinates = zip(latitude, longitude).map(CLLocationCoordinate2D.init)

    AppLogger.logInfo("\(coordinates)")

   let annotations = zip(coordinates, names)
       .map { (coordinate, name) -> MKPointAnnotation in
           let annotation = MKPointAnnotation()

           annotation.coordinate = coordinate
           annotation.title = name

           return annotation
       }

   mapView.addAnnotations(annotations)
   mapView.showAnnotations(annotations, animated: true)
}


func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    guard annotation is MKPointAnnotation else { return nil }

    let identifier = "Annotation"
    var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)

    if annotationView == nil {
        annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
        annotationView!.canShowCallout = true
    } else {
        annotationView!.annotation = annotation
    }
    return annotationView
}

[__C.CLLocationCoordinate2D(纬度:41.89454659591164,经度:-87.67463844121563),__C.CLLocationCoordinate2D(纬度:41.89424383424124,经度:-87.67461071330482))]

预期的结果是,当显示 mapView 时,我们会看到引脚(注释),以及将它们从第一个引脚连接到最后一个引脚的多边形线。我可以稍后处理的绘制多边形。

标签: iosswiftannotationsmkmapview

解决方案


viewFor如果您为您的注释注册您的注释视图,您是正确的,例如

mapView.register(MKPinAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier))

但是,让我们暂时搁置一下。让我们关注未显示的注释。有两种可能:

  1. 确保您实际上是在添加坐标。

    你在打印coordinates。尝试打印annotations。即,让我们确保名称不为空,因此注释为空。如果您zip/map一个非空数组带有一个空数组,则最终结果将为空。(它被缩短到最小数组长度。)

  2. 确保你viewFor被叫到。

    假设您已经解决了第一个问题,请尝试添加断点或登录语句viewFor并确保它被调用。例如,确保您设置了地图视图的委托等。


推荐阅读