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

时间:2010-01-25 12:26:50

标签: iphone mkmapview mkannotation

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

[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]]; 
       } 
    }

7 个答案:

答案 0 :(得分:58)

查看MKMapView documentation,您似乎可以使用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];

希望这有帮助,

萨姆

答案 1 :(得分:31)

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

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

我认为这与上面发布的手动过滤器几乎相同,只是使用谓词来执行脏工作。

答案 2 :(得分: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];

答案 3 :(得分:8)

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

[self.mapView removeAnnotations:self.mapView.annotations];

答案 4 :(得分:6)

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

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

        [map removeAnnotation:annotation];
    }
    }

我像这样修改了

答案 5 :(得分: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];

答案 6 :(得分:0)

对于Swift 3.0

for annotation in self.mapView.annotations {
    if let _ = annotation as? MKUserLocation {
       // keep the user location
    } else {
       self.mapView.removeAnnotation(annotation)
    }
}