6
votes

I am loading a mapview with a single annotation. Just like the "map app" in iphone. I have a search bar, which shows the address of the pin location, shown in map. Now I decide to change the location address. I type a new address location in the search bar. Then my mapview has to remove the existing annotation and add the new annotation. Right now, I am adding the new annotation, but I am unable to remove the existing annotation. How can I remove that existing annotation?

2

2 Answers

8
votes

First, get the list of annotations on the map view, and then remove the annotations that are not the current user location (i.e. in the MKUserLocation class).

NSArray *annotations = [mapView annotations];
for (id annotation in annotations) {
    if (annotation isKindOfClass:[MKUserLocation class]) {
        continue;
    }
    [mapView removeAnnotation:annotation];
}

Then you can add your new annotation as normal.

0
votes

If you're using custom annotations another way could be this:

for (int i =0; i < [mapView.annotations count]; i++) { 
    if ([[mapView.annotations objectAtIndex:i] isKindOfClass:[MyAnnotationClass class]]) {                      
         [mapView removeAnnotation:[mapView.annotations objectAtIndex:i]]; 
       } 
    }

In this way remove just the annotations you have added.