I've an NSArray
of custom MKAnnotation
, i need to set a red pin color for the first/last annotation, otherwise set a green pin.
The program does not behave as i want, the green pins are associated each time with two different annotations in a random way, are not associated with the first and the last as i want.
So, this is what i'm doing in my controller:
- (void)viewDidLoad
{
[super viewDidLoad];
//load set a coords from file etc...
//self.coordinates is the array of annotations
[self.myMap addAnnotations:self.coordinates];
}
then in the viewForAnnotation: callback:
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{
NSString *ident = @"MY_IDENTIFIER";
MKPinAnnotationView *annView=(MKPinAnnotationView *)[self.myMap dequeueReusableAnnotationViewWithIdentifier:ident];
if(self.myMap.userLocation==annotation){
return nil;
}
if(annView == nil){
annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:ident];
annView.animatesDrop=TRUE;
annView.canShowCallout = YES;
annView.rightCalloutAccessoryView=[UIButton buttonWithType:UIButtonTypeDetailDisclosure];
annView.calloutOffset = CGPointMake(-5, 5);
int currIdxAnn=[self.myMap.annotations indexOfObject:annotation];
int lastIdxAnn=[self.myMap.annotations indexOfObject:[self.myMap.annotations lastObject]];
/*
if (currIdxAnn==0 || currIdxAnn==lastIdxAnn) {
annView.pinColor=MKPinAnnotationColorRed;
}else {
annView.pinColor=MKPinAnnotationColorGreen;
}*/
CustomAnnotation *an=(CustomAnnotation *)annotation;
if (an.tag==98||an.tag==99) {
annView.pinColor=MKPinAnnotationColorGreen;
}else {
annView.pinColor=MKPinAnnotationColorRed;
}
}
return annView;
}
It seems that the method addAnnotations:
does not work as I believe, probably loads the annotations with an order different from the array. Is it possible?
I also tried to make a similar process in didAddAnnotationViews:
but without good results.
Some hints? Thanks.
PS:as I finished writing this question i found this response, and seems to confirm my theory. Someone has already encountered a similar problem?
EDIT: After several tests i realized that the best way to accomplish what i want is to first set a tag to my first/last annotations:
CustomAnnotation *first=[self.coordinates objectAtIndex:0];
first.tag=98;
CustomAnnotation *last=[self.coordinates objectAtIndex:[self.coordinates indexOfObject:[self.coordinates lastObject]]];
last.tag=99;
Then as you can see i have slightly modified the viewForAnnotation
to understand the annotation was the one I looked for.
Then the trick was just calling the function that adds the annotations in a background thread, like:
[self performSelectorInBackground:@selector(addAllAnnot) withObject:nil];
-(void)addAllAnnot{
[self.myMap addAnnotations:self.coordinates];
}
This worked for me after a week of testing, if anyone has any better idea, it will be appreciated.