Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Annotations in MapKit - Programmatically

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?

like image 523
H.N. Avatar asked Nov 09 '16 18:11

H.N.


People also ask

How do you add annotations in Mkmapview?

Start by making your view controller the delegate of your map view, so that we can receive events. You should also make your view controller conform to MKMapViewDelegate in code. Second, you need to implement a viewFor method that converts your annotation into a view that can be displayed on the map.

What is Mkplacemark?

A user-friendly description of a location on the map.

How do I remove annotations in mapView?

To remove a single annotation from an annotation manager, remove it from the annotations array. To completely remove an annotation manager, call mapView. annotations.


1 Answers

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)
}
like image 85
zisoft Avatar answered Oct 11 '22 17:10

zisoft