How to remove all annotations from MKMapView witho

2019-01-16 13:05发布

I would like to remove all annotations from my mapview without the blue dot of my position. When I call:

[mapView removeAnnotations:mapView.annotations];

all annotations are removed.

In which way can I check (like a for loop on all the annotations) if the annotation is not the blue dot annotation?

EDIT (I've solved with this):

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

7条回答
不美不萌又怎样
2楼-- · 2019-01-16 13:24

For Swift 3.0

for annotation in self.mapView.annotations {
    if let _ = annotation as? MKUserLocation {
       // keep the user location
    } else {
       self.mapView.removeAnnotation(annotation)
    }
}
查看更多
家丑人穷心不美
3楼-- · 2019-01-16 13:25
for (id annotation in map.annotations) {
    NSLog(@"annotation %@", annotation);

    if (![annotation isKindOfClass:[MKUserLocation class]]){

        [map removeAnnotation:annotation];
    }
    }

i modified like this

查看更多
男人必须洒脱
4楼-- · 2019-01-16 13:26

Isn't it easier to just do the following:

//copy your annotations to an array
    NSMutableArray *annotationsToRemove = [[NSMutableArray alloc] initWithArray: mapView.annotations]; 
//Remove the object userlocation
    [annotationsToRemove removeObject: mapView.userLocation]; 
 //Remove all annotations in the array from the mapView
    [mapView removeAnnotations: annotationsToRemove];
    [annotationsToRemove release];
查看更多
forever°为你锁心
5楼-- · 2019-01-16 13:27

it easier to just do the following:

NSMutableArray *annotationsToRemove = [NSMutableArray arrayWithCapacity:[self.mapView.annotations count]];
    for (int i = 1; i < [self.mapView.annotations count]; i++) {
        if ([[self.mapView.annotations objectAtIndex:i] isKindOfClass:[AddressAnnotation class]]) {
            [annotationsToRemove addObject:[self.mapView.annotations objectAtIndex:i]];
            [self.mapView removeAnnotations:annotationsToRemove];
        }
    }

[self.mapView removeAnnotations:annotationsToRemove];
查看更多
欢心
6楼-- · 2019-01-16 13:29

shortest way to clean all annotations and preserving MKUserLocation class annotation

[self.mapView removeAnnotations:self.mapView.annotations];
查看更多
手持菜刀,她持情操
7楼-- · 2019-01-16 13:37

If you like quick and simple, there's a way to filter an array of the MKUserLocation annotation. You can pass this into MKMapView's removeAnnotations: function.

 [_mapView.annotations filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"!(self isKindOfClass: %@)", [MKUserLocation class]]];

I assume this is pretty much the same as the manual filters posted above, except using a predicate to do the dirty work.

查看更多
登录 后发表回答