Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove all map annotations in swift 2

I had working code to remove all map annotations with a button, but after my update to xcode 7 I am running into the error:

Type 'MKAnnotation' does not conform to protocol 'SequenceType'

if let annotations = (self.mapView.annotations as? MKAnnotation){
    for _annotation in annotations {
        if let annotation = _annotation as? MKAnnotation {
            self.mapView.removeAnnotation(annotation)
        }
    }
}
like image 873
user4812000 Avatar asked Sep 29 '15 17:09

user4812000


4 Answers

In Swift 2 annotations is declared as non optional array [MKAnnotation] so you can easily write

let allAnnotations = self.mapView.annotations
self.mapView.removeAnnotations(allAnnotations)

without any type casting.

like image 157
vadian Avatar answered Nov 04 '22 13:11

vadian


self.mapView.removeAnnotations(self.mapView.annotations)

If you don't want remove user location.

self.mapView.annotations.forEach {
  if !($0 is MKUserLocation) {
    self.mapView.removeAnnotation($0)
  }
}

Note: Objective-C now have generics, it is no longer necessary cast the elements of 'annotations' array.

like image 22
Daniel Avatar answered Nov 04 '22 11:11

Daniel


SWIFT 5

If you don't want to remove user location mark:

let annotations = mapView.annotations.filter({ !($0 is MKUserLocation) })
mapView.removeAnnotations(annotations)
like image 5
Christopher Lowiec Avatar answered Nov 04 '22 12:11

Christopher Lowiec


The issue is that there are two methods. One is removeAnnotation which takes an MKAnnotation object, and the other is removeAnnotations which takes an array of MKAnnotations, note the "s" at the end of one and not the other. Attempting to cast from [MKAnnotation], an array to MKAnnotation a single object or visa versa will crash the program. The line of code self.mapView.annotations creates an array. Thus, if you are using the method removeAnnotation, you need to index the array for a single object within the array, as seen below:

let previousAnnotations = self.mapView.annotations
if !previousAnnotations.isEmpty{
  self.mapView.removeAnnotation(previousAnnotations[0])
}

Thus, you can remove various annotations while keeping the users location. You should always test your array before attempting to remove objects from it, else there is the possibly getting an out of bounds or nil error.

Note: using the method removeAnnotations (with an s)removes all annotations. If you are getting a nil, that implies that you have an empty array. You can verify that by adding an else statement after the if, like so;

    else{print("empty array")}
like image 1
ZaneMan Avatar answered Nov 04 '22 11:11

ZaneMan