0

I have a lot of annotations on the mapView and user location dot. Then, if user tap for 2 sec. on the map, I add an extra annotation with options. I need to remove that last added annotation from map by pressing the button. How can I remove it without to remove any other annotation?

- (void)addPin:(UILongPressGestureRecognizer*)recognizer { 
    if(UIGestureRecognizerStateBegan == recognizer.state) {


        CGPoint tappedPoint = [recognizer locationInView:mapView];

        CLLocationCoordinate2D locCoord= [mapView convertPoint:tappedPoint toCoordinateFromView:mapView];


        MKPointAnnotation *annot = [[MKPointAnnotation alloc] init];
        annot.coordinate = locCoord;
        [self.mapView addAnnotation:annot];

    }

    if(UIGestureRecognizerStateChanged == recognizer.state) {
        // Do repeated work here (repeats continuously) while finger is down
    }

    if(UIGestureRecognizerStateEnded == recognizer.state) {
        // Do end work here when finger is lifted
    }
}
Pavel Kaljunen
  • 1,291
  • 2
  • 26
  • 53
  • See http://stackoverflow.com/questions/17892362/how-to-delete-the-last-annotation-on-a-mapview –  Sep 05 '13 at 13:56

5 Answers5

4

To remove all the annotations from map view:

[vwMap removeAnnotations:vwMap.annotations];

PS: vwMap is the MKMap view object

pkc456
  • 8,350
  • 38
  • 53
  • 109
2

Do the following,

If you have the annotation object

[self.mapView removeAnnotation:annot];

If you have the index of the object

[self.mapView removeAnnotation:self.mapView.annotations.lastObject];
Omar Abdelhafith
  • 21,163
  • 5
  • 52
  • 56
0

Do this to remove your last added annotation in your delete Action:

[self.mapView removeAnnotation:[self.mapView.annotations lastObject]];

Hope helpful

Paresh Navadiya
  • 38,095
  • 11
  • 81
  • 132
0

I managed to remove the annotation object that is touched by doing the following, I know this wasn't the question but it may help someone out

set the mapView as delegate

- (void)mapView:(MKMapView *)thisMapView didSelectAnnotationView:(MKAnnotationView *)view {

MKPointAnnotation *thisTouchedAnnotation = view.annotation;

uint8_t annotationCount = thisMapView.annotations.count;

for(int i =0; i<annotationCount; i++)
{
    if ([thisMapView.annotations objectAtIndex:i]==thisTouchedAnnotation){
        [thisMapView removeAnnotation:[mapView.annotations objectAtIndex:i]];
        break;
    }

   }
}

not flawless code but it may guide you :-)

r farnell
  • 71
  • 4
0

Use this code!

NSArray *array=self.mapview.annotations;
for (MKPointAnnotation *anno in array)
{
    if(anno==[array lastObject])
    {
        [self.mapview removeAnnotation:anno];
    }
}
bharathi kumar
  • 210
  • 2
  • 8