Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete all Annotations on a MKMapView

Is there a simple way to delete all the annotations on a map without iterating through all the displayed annotations in Objective-c?

like image 750
kevin Mendoza Avatar asked Jun 12 '10 03:06

kevin Mendoza


People also ask

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.


2 Answers

Yes, here is how

[mapView removeAnnotations:mapView.annotations] 

However the previous line of code will remove all map annotations "PINS" from the map, including the user location pin "Blue Pin". To remove all map annotations and keep the user location pin on the map, there are two possible ways to do that

Example 1, retain the user location annotation, remove all pins, add the user location pin back, but there is a flaw with this approach, it will cause the user location pin to blink on the map, due to removing the pin then adding it back

- (void)removeAllPinsButUserLocation1  {     id userLocation = [mapView userLocation];     [mapView removeAnnotations:[mapView annotations]];      if ( userLocation != nil ) {         [mapView addAnnotation:userLocation]; // will cause user location pin to blink     } } 

Example 2, I personally prefer to avoid removing the location user pin in the first place,

- (void)removeAllPinsButUserLocation2 {     id userLocation = [mapView userLocation];     NSMutableArray *pins = [[NSMutableArray alloc] initWithArray:[mapView annotations]];     if ( userLocation != nil ) {         [pins removeObject:userLocation]; // avoid removing user location off the map     }      [mapView removeAnnotations:pins];     [pins release];     pins = nil; } 
like image 51
RocketMan Avatar answered Sep 18 '22 18:09

RocketMan


Here is the simplest way to do that:

-(void)removeAllAnnotations {   //Get the current user location annotation.   id userAnnotation=mapView.userLocation;    //Remove all added annotations   [mapView removeAnnotations:mapView.annotations];     // Add the current user location annotation again.   if(userAnnotation!=nil)   [mapView addAnnotation:userAnnotation]; } 
like image 28
Sandip Sarkar Avatar answered Sep 20 '22 18:09

Sandip Sarkar