在MapKit中编程添加注释

6

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

我已经定义了以下内容:

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

这些点都有坐标,我已经确认过了。接下来我执行以下操作:

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

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

6
每个注释需要是一个新的实例,你只使用了一个实例并覆盖了它的坐标。所以请更改你的代码:
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)
}

谢谢。我会在几个小时内尝试并报告结果。是否可以通过标题删除注释? - H.N.
要删除注释,只需遍历map.annotations数组,直到找到该注释。然后调用map.removeAnnotation(annotation) - zisoft

5

您可以使用以下代码编辑您的for循环。我认为您的数组可能类似于points数组。

  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)
}

对我来说运行正常。祝你一切顺利。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接