Why will my code not remove the map annotation?
I hit the button and it gets the users location and then pins it to the map. The problem is that when the button is hit a second, third, ....... time It just keeps adding pins instead of removing the first pin (simulating replacing the pin).
I have tried adding another button (clear pins) and following this thread :http://stackoverflow.com/questions/3027392/how-to-delete-all-annotations-on-a-mkmapview but the app just crashes with no debug info.
But in theory my code should work. So what am I not understanding?
- (IBAction)getLocation:(id)sender {
MapAnnotation *ann1 =[[[MapAnnotation alloc] init]autorelease];
// remove annotation
[mapView removeAnnotation:ann1];
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter=kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
[locationManager startUpdatingLocation];
[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
MKCoordinateRegion region = {{0.0,0.0},{0.0,0.0}};
region.center.latitude = locationManager.location.coordinate.latitude;
region.center.longitude = locationManager.location.coordinate.longitude;
region.span.longitudeDelta = 0.005f;
region.span.latitudeDelta = 0.005f;
[mapView setRegion:region animated:YES];
[mapView setDelegate:sender];
MKCoordinateRegion location1;
location1.center.latitude =locationManager.location.coordinate.latitude;
location1.center.longitude= locationManager.location.coordinate.longitude;
location1.span.longitudeDelta=0.1;
location1.span.latitudeDelta =0.1;
// Add Annotation
//MapAnnotation *ann1 =[[MapAnnotation alloc] init];
ann1.title=@"You Parked Here";
ann1.subtitle=@"";
ann1.coordinate= location1.center;
[mapView addAnnotation:ann1];
}
You're removing an annotation that you just created, and which hasn't been added to the map:
MapAnnotation *ann1 =[[[MapAnnotation alloc] init]autorelease];
// remove annotation
[mapView removeAnnotation:ann1];
You can either locate the annotation on the map, and then remove it, or you can take a heavy-handed approach and simply remove all the annotations in one swoop. Since I don't know the UI interaction, I can't really outline how to locate the annotation for you. However, here's how to remove all:
NSMutableArray *annotations = [NSMutableArray array];
for (id annotation in [mapView annotations])
{
[annotations addObject:annotation];
}
[mapView removeAnnotations:annotations];
HTH.