26

我想从我的地图视图中删除所有注释,而我的位置没有蓝点。当我打电话时:

[mapView removeAnnotations:mapView.annotations];

所有注释都被删除。

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

编辑(我已经解决了这个问题):

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

7 回答 7

58

查看MKMapView 文档,您似乎可以使用 annotations 属性。遍历它并查看您有哪些注释应该非常简单:

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

您还拥有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];

希望这可以帮助,

山姆

于 2010-01-25T12:38:40.093 回答
31

如果您喜欢快速和简单,可以使用一种过滤 MKUserLocation 注释数组的方法。您可以将其传递给 MKMapView 的 removeAnnotations: 函数。

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

我认为这与上面发布的手动过滤器几乎相同,除了使用谓词来完成肮脏的工作。

于 2010-05-26T16:50:46.630 回答
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];
于 2012-03-22T17:28:26.177 回答
8

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

[self.mapView removeAnnotations:self.mapView.annotations];
于 2013-09-20T08:58:26.460 回答
6
for (id annotation in map.annotations) {
    NSLog(@"annotation %@", annotation);

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

        [map removeAnnotation:annotation];
    }
    }

我这样修改

于 2011-08-16T06:05:58.040 回答
1

执行以下操作更容易:

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];
于 2012-12-13T13:23:12.563 回答
0

对于 Swift 3.0

for annotation in self.mapView.annotations {
    if let _ = annotation as? MKUserLocation {
       // keep the user location
    } else {
       self.mapView.removeAnnotation(annotation)
    }
}
于 2017-04-17T12:42:26.720 回答