【问题标题】:Add Annotations in MapKit - Programmatically在 MapKit 中添加注释 - 以编程方式
【发布时间】:2016-11-09 18:21:07
【问题描述】:

我正在尝试向我的地图添加注释。 我有一个带有坐标的点数组。 我正在尝试从这些坐标添加注释。

我已经定义了:

var points: [CLLocationCoordinate2D] = [CLLocationCoordinate2D]() 
let annotation = MKPointAnnotation()

points 里面有坐标。我检查了。我这样做:

for index in 0...points.count-1 {
        annotation.coordinate = points[index]
        annotation.title = "Point \(index+1)"
        map.addAnnotation(annotation)
    }

它只添加最后一个注释......而不是所有注释。 为什么是这样? 顺便问一下,有没有办法删除指定的注释,例如按标题?

【问题讨论】:

    标签: swift mapkit swift3 mkpointannotation


    【解决方案1】:

    每个注释都需要是一个新实例,您只使用一个实例并覆盖其坐标。所以改变你的代码:

    for index in 0...points.count-1 {
        let annotation = MKPointAnnotation()  // <-- new instance here
        annotation.coordinate = points[index]
        annotation.title = "Point \(index+1)"
        map.addAnnotation(annotation)
    }
    

    【讨论】:

    • 谢谢。将在几个小时内尝试并报告。是否可以按标题删除注释?
    • 要删除注解,只需遍历map.annotations 数组,直到找到注解。然后拨打map.removeAnnotation(annotation)
    【解决方案2】:

    您可以使用以下代码编辑您的 for 循环 我认为你的数组会像点数组

      let points = [
        ["title": "New York, NY",    "latitude": 40.713054, "longitude": -74.007228],
        ["title": "Los Angeles, CA", "latitude": 34.052238, "longitude": -118.243344],
        ["title": "Chicago, IL",     "latitude": 41.883229, "longitude": -87.632398]
    ]
    for point in points {   
        let annotation = MKPointAnnotation()
        annotation.title = point["title"] as? String
        annotation.coordinate = CLLocationCoordinate2D(latitude: point["latitude"] as! Double, longitude: point["longitude"] as! Double)
        mapView.addAnnotation(annotation)
    }
    

    它对我有用。祝你一切顺利。

    【讨论】:

      猜你喜欢
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 2013-06-17
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多