如何在不删除蓝点的情况下从MKMapView中删除所有注释?

Mat*_*Mat 26 iphone mkmapview mkannotation

我想从我的mapview中删除所有注释,而不是我的位置的蓝点.我打电话的时候:

[mapView removeAnnotations:mapView.annotations];
Run Code Online (Sandbox Code Playgroud)

删除所有注释.

如果注释不是蓝点注释,我可以通过哪种方式检查(如所有注释的for循环)?

编辑(我用这个解决了):

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

dea*_*rne 58

查看MKMapView文档,您似乎可以使用annotations属性.迭代这个并看看你有什么注释应该很简单:

for (id annotation in myMap.annotations) {
    NSLog(@"%@", annotation);
}
Run Code Online (Sandbox Code Playgroud)

您还拥有该userLocation属性,该属性为您提供表示用户位置的注释.如果您浏览注释并记住所有不是用户位置的注释,则可以使用以下removeAnnotations:方法删除它们:

NSInteger toRemoveCount = myMap.annotations.count;
NSMutableArray *toRemove = [NSMutableArray arrayWithCapacity:toRemoveCount];
for (id annotation in myMap.annotations)
    if (annotation != myMap.userLocation)
        [toRemove addObject:annotation];
[myMap removeAnnotations:toRemove];
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助,

山姆


Seb*_*ean 31

如果您喜欢快速而简单,可以使用过滤MKUserLocation注释的数组.您可以将其传递给MKMapView的removeAnnotations:函数.

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

我假设这与上面发布的手动过滤器非常相似,除了使用谓词来执行脏工作.


Mik*_*ael 13

是不是更容易做到以下几点:

//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];
Run Code Online (Sandbox Code Playgroud)

  • 这是最好的答案! (5认同)

Daz*_*ong 8

清除所有注释并保留MKUserLocation类注释的最短方法

[self.mapView removeAnnotations:self.mapView.annotations];
Run Code Online (Sandbox Code Playgroud)


chi*_*228 6

for (id annotation in map.annotations) {
    NSLog(@"annotation %@", annotation);

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

        [map removeAnnotation:annotation];
    }
    }
Run Code Online (Sandbox Code Playgroud)

我这样修改了