[objective-c] MKMapView에서 모든 주석을 삭제하는 방법

Objective-c에 표시된 모든 주석을 반복하지 않고지도의 모든 주석을 삭제하는 간단한 방법이 있습니까?



답변

예, 방법은 다음과 같습니다.

[mapView removeAnnotations:mapView.annotations]

그러나 이전 코드 줄은 사용자 위치 핀 “파란색 핀”을 포함하여 모든 맵 주석 “PINS”를 맵에서 제거합니다. 모든지도 주석을 제거하고지도에 사용자 위치 핀을 유지하려면 두 가지 방법이 있습니다.

예 1, 사용자 위치 주석을 유지하고 모든 핀을 제거하고 사용자 위치 핀을 다시 추가하지만이 방법에는 결함이 있습니다. 핀을 제거한 다음 추가하기 때문에 사용자 위치 핀이지도에서 깜박이게됩니다. 뒤

- (void)removeAllPinsButUserLocation1 
{
    id userLocation = [mapView userLocation];
    [mapView removeAnnotations:[mapView annotations]];

    if ( userLocation != nil ) {
        [mapView addAnnotation:userLocation]; // will cause user location pin to blink
    }
}

예 2, 개인적으로 위치 사용자 핀을 제거하지 않는 것이 좋습니다.

- (void)removeAllPinsButUserLocation2
{
    id userLocation = [mapView userLocation];
    NSMutableArray *pins = [[NSMutableArray alloc] initWithArray:[mapView annotations]];
    if ( userLocation != nil ) {
        [pins removeObject:userLocation]; // avoid removing user location off the map
    }

    [mapView removeAnnotations:pins];
    [pins release];
    pins = nil;
}


답변

이를 수행하는 가장 간단한 방법은 다음과 같습니다.

-(void)removeAllAnnotations
{
  //Get the current user location annotation.
  id userAnnotation=mapView.userLocation;

  //Remove all added annotations
  [mapView removeAnnotations:mapView.annotations]; 

  // Add the current user location annotation again.
  if(userAnnotation!=nil)
  [mapView addAnnotation:userAnnotation];
}


답변

이 답변을 다시 찾을 것이라고 상상하기 때문에 명시 적으로 작성된 사용자 위치를 제외한 모든 주석을 제거하는 방법은 다음과 같습니다.

NSMutableArray *locs = [[NSMutableArray alloc] init];
for (id <MKAnnotation> annot in [mapView annotations])
{
    if ( [annot isKindOfClass:[ MKUserLocation class]] ) {
    }
    else {
        [locs addObject:annot];
    }
}
[mapView removeAnnotations:locs];
[locs release];
locs = nil;


답변

이것은 Sandip의 대답과 매우 유사하지만 사용자 위치를 다시 추가하지 않으므로 파란색 점이 다시 깜박이지 않습니다.

-(void)removeAllAnnotations
{
    id userAnnotation = self.mapView.userLocation;

    NSMutableArray *annotations = [NSMutableArray arrayWithArray:self.mapView.annotations];
    [annotations removeObject:userAnnotation];

    [self.mapView removeAnnotations:annotations];
}


답변

사용자 위치에 대한 참조를 저장할 필요가 없습니다. 필요한 것은 다음과 같습니다.

[mapView removeAnnotations:mapView.annotations]; 

mapView.showsUserLocation설정하는 YES한지도에 사용자 위치가 계속 표시됩니다. YES기본적 으로이 속성을 설정 하면지도보기에 사용자 위치 업데이트 및 가져 오기를 시작하여지도에 표시하도록 요청합니다. 로부터 MKMapView.h의견 :

// Set to YES to add the user location annotation to the map and start updating its location


답변

Swift 버전 :

func removeAllAnnotations() {
    let annotations = mapView.annotations.filter {
        $0 !== self.mapView.userLocation
    }
    mapView.removeAnnotations(annotations)
}


답변

스위프트 3

if let annotations = self.mapView.annotations {
    self.mapView.removeAnnotations(annotations)
}