6

I am trying to add annotations to my map. I have an array of points with coordinates inside. I am trying to add annotations from those coordinates.

I have this defined:

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

points has coordinates inside. I checked. And I do this:

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

It keeps adding only the last annotation... Instead of all of them. Why is this? By the way, is there a way to delete a specified annotation, by title for example?

H.N.
  • 1,207
  • 2
  • 12
  • 28

2 Answers2

6

Each annotation needs to be a new instance, you are using only one instance and overriding its coordinates. So change your code:

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)
}
zisoft
  • 22,770
  • 10
  • 62
  • 73
  • Thanks. Will try it in a couple of hours and report. Is it possible to dele te annotations by title? – H.N. Nov 09 '16 at 18:54
  • To delete an annotation just iterate over the `map.annotations` array until you found the annotation. Then call `map.removeAnnotation(annotation)` – zisoft Nov 10 '16 at 12:34
5

You can edit your for loop with the below code I think your array would be like points array

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

it's working for me. All the best for you.

Harish Singh
  • 765
  • 1
  • 12
  • 23