2016-11-09 88 views
3

我想向我的地图添加注释。 我有一个坐标里面的点的数组。 我想从这些坐标添加注释。在MapKit中添加注释 - 以编程方式

我有这样的定义:

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

它不断添加最后一个注释...而不是所有的人。 这是为什么? 顺便说一下,有没有一种方法来删除指定的注释,例如按标题?

回答

3

每个注解需要是一个新的实例,您只使用一个实例并覆盖其坐标。因此,更改代码:

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

谢谢。将在几个小时内尝试并报告。是否可以按标题删除注释? –

+0

它工作。谢谢 –

+0

要删除注释,只需遍历'map.annotations'数组,直到找到注释为止。然后调用'map.removeAnnotation(注解)' – zisoft

2

您可以编辑与下面的代码 循环,我认为你的阵列将像点阵列

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

它为我工作。祝你一切安好。