iphoneobjective-cannotationsmkmapviewmapkit

How to remove previous Annotation pin when adding another one?


I have a UITableView and each cell contains a Map button. When I tap each button, Map view is shown and corresponding Annotation pin is added.

This code is called when I tap each map button,

    double tempLatitude  = [[[myDict objectForKey:key] objectAtIndex:15] doubleValue];
    double tempLongitude = [[[myDict objectForKey:key] objectAtIndex:16] doubleValue];
                                                  // key is the cell index.

         //--** Setting the Latitude and Longitude 
         CLLocationCoordinate2D myCoordinate;

         myCoordinate.latitude  = tempLatitude;
         myCoordinate.longitude = tempLongitude;

         MyMapAnnotation *MyAnnotation = [[[MyMapAnnotation alloc] initWithCoordinate:myCoordinate addressDictionary:nil]autorelease];
         MyAnnotation.title            = [[myDict objectForKey:key] objectAtIndex:1];
         MyAnnotation.subtitle         = [NSString  stringWithFormat:@"%f %f", MyAnnotation.coordinate.latitude, MyAnnotation.coordinate.longitude];

And this is the code of MyMapAnnotation,

    @synthesize coordinate = theCoordinate;
    @synthesize title = theTitleAnnotation;
    @synthesize subtitle = theSubTitleAnnotation;



    - (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate addressDictionary:(NSDictionary *)addressDictionary 
    {

      if ((self = [super initWithCoordinate:coordinate addressDictionary:addressDictionary]))
      {
         self.coordinate = coordinate;
      }
         return self;
    }

Everything works fine. Now, when I tap one button, corresponding annotation pin is shown and when I tap second button, the previous pin is still there and second annotation pin is also being added.

But

What I want is,

When I tap each button, the previous annotation pin should be removed and only the current annotation pin should be added.

How can I identify the previous pin?

And where can I give this code [mapView removeAnnotation:annotationToRemove] ??

EDIT: Obviously, the 'previous annotation pin' is the 'annotationToRemove'. I know this. My question is, How can I identify this previous annotation pin to specify as 'annotationToRemove'??

Thanks :-)


Solution

  • have you try with [myMap removeAnntoation:[myMap.annotations objectAtIndex:0]]; ?

    EDIT: There are several ways to do this, one is to set a tag to the annotation, then search it by tag; another way is to check all annotations and then remove that which you want, if your problem is to remove the previous annotation added, you can call:

    [myMap removeAnntoation:[myMap.annotations lastObject]];

    P.S: if you have myMap.showsUserLocation=YES; look this: How to remove all annotations from MKMapView without removing the blue dot?.