Как удалить все аннотации из MKMapView, не удаляя синюю точку? - PullRequest
26 голосов
/ 25 января 2010

Я хотел бы удалить все аннотации из моего обзора карты без синей точки моей позиции. Когда я звоню:

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

58 голосов
/ 25 января 2010

Глядя на документацию 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];

Надеюсь, это поможет,

Sam

31 голосов
/ 26 мая 2010

Если вам нравится быстро и просто, есть способ отфильтровать массив аннотации MKUserLocation. Вы можете передать это в функцию removeAnnotations: MKMapView.

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

Я предполагаю, что это почти то же самое, что и ручные фильтры, опубликованные выше, за исключением использования предиката для грязной работы.

13 голосов
/ 22 марта 2012

Не проще ли просто сделать следующее:

//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];
8 голосов
/ 20 сентября 2013

кратчайший способ очистки всех аннотаций и сохранения аннотации класса MKUserLocation

[self.mapView removeAnnotations:self.mapView.annotations];
6 голосов
/ 16 августа 2011
for (id annotation in map.annotations) {
    NSLog(@"annotation %@", annotation);

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

        [map removeAnnotation:annotation];
    }
    }

я изменил вот так

1 голос
/ 13 декабря 2012

проще всего сделать следующее:

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];
0 голосов
/ 17 апреля 2017

для Swift 3.0

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