Here is my viewForAnnotation: When in loop, viewForAnnotation returns nil. When i add the self.customAnnotation (alloc) line to the viewDidLoad statement or call it by itself, there is no problems and annotation = self.customAnnotation. When in loop, annotation looses the self.customAnnotation.
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
NSLog(@"viewForAnnotation");
//if (annotation == self.mapView.userLocation) return nil;
if (annotation == self.calloutAnnotation) {
CalloutMapAnnotationView *calloutMapAnnotationView = (CalloutMapAnnotationView *)[self.mapView dequeueReusableAnnotationViewWithIdentifier:@"CalloutAnnotation"];
if (!calloutMapAnnotationView) {
calloutMapAnnotationView = [[AccessorizedCalloutMapAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"CalloutAnnotation"];
calloutMapAnnotationView.contentHeight = 78.0f;
UIImage *asynchronyLogo = [UIImage imageNamed:@"asynchrony-logo-small.png"];
UIImageView *asynchronyLogoView = [[UIImageView alloc] initWithImage:asynchronyLogo];
asynchronyLogoView.frame = CGRectMake(5,2,asynchronyLogoView.frame.size.width,asynchronyLogoView.frame.size.height);
[calloutMapAnnotationView.contentView addSubview:asynchronyLogoView];
}
calloutMapAnnotationView.parentAnnotationView = self.selectedAnnotationView;
calloutMapAnnotationView.mapView = self.mapView;
return calloutMapAnnotationView;
} else if (annotation == self.customAnnotation) {
MKPinAnnotationView *annotationView = [[BasicMapAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"CustomAnnotation"];
annotationView.canShowCallout = NO;
annotationView.pinColor = MKPinAnnotationColorGreen;
return annotationView;
}
return nil;
}
Here is the actual loop assigned to a button for action:
- (IBAction)drawMap:(id)sender {
NSURL *url = [NSURL URLWithString:@"myurl"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSArray *array = [NSJSONSerialization JSONObjectWithData:data
options:0
error:&error];
if (error != nil)
{
// handle the error as you want
}
//CLLocationCoordinate2D location;
//MKPointAnnotation *newAnnotation;
NSMutableArray *newAnnotations = [NSMutableArray array];
for (NSDictionary *dictionary in array)
{
self.customAnnotation = [[BasicMapAnnotation alloc] initWithLatitude:[dictionary[@"latitude"] doubleValue] andLongitude:[dictionary[@"longitude"] doubleValue]];
[newAnnotations addObject:self.customAnnotation];
}
[self.mapView addAnnotations:newAnnotations];
[self zoomToFitMapAnnotations:self.mapView];
}
Anna's solution worked!
In viewForAnnotation, instead of if (annotation == self.customAnnotation), you should use if ([annotation isKindOfClass:[BasicMapAnnotation class]]) because self.customAnnotation only points to one annotation at a time and there's no guarantee that viewForAnnotation will get called one at a time after each add. – Anna Jun 6 '14 at 2:22