Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove all annotations from MKMapView except the user location annotation?

I use removeAnnotations to remove my annotations from mapView but same it remove user location ann. How can I prevent this, or how to get user ann back to view?

NSArray *annotationsOnMap = mapView.annotations;         [mapView removeAnnotations:annotationsOnMap]; 
like image 273
Pavel Kaljunen Avatar asked Jun 02 '12 19:06

Pavel Kaljunen


2 Answers

Update:

When I tried with the iOS 9 SDK the user annotation is no longer removed. You can simply use

mapView.removeAnnotations(mapView.annotations) 

Historical answer (for apps that run on iOS before iOS 9):

Try this:

NSMutableArray * annotationsToRemove = [ mapView.annotations mutableCopy ] ; [ annotationsToRemove removeObject:mapView.userLocation ] ; [ mapView removeAnnotations:annotationsToRemove ] ; 

EDIT: Swift version

let annotationsToRemove = mapView.annotations.filter { $0 !== mapView.userLocation } mapView.removeAnnotations( annotationsToRemove ) 
like image 144
nielsbot Avatar answered Oct 04 '22 15:10

nielsbot


To clear all the annotations from the map:

[self.mapView removeAnnotations:[self.mapView annotations]]; 

To remove specified annotations from Mapview

 for (id <MKAnnotation> annotation in self.mapView.annotations) {     if (![annotation isKindOfClass:[MKUserLocation class]])     {               [self.mapView removeAnnotation:annotation];        }  } 

Hope this may help you.

like image 38
Aswathy Bose Avatar answered Oct 04 '22 14:10

Aswathy Bose