Dynamic Annotations (MKAnnotationView) for iOS MapKit
Author: Mohith KM
Annotations in a map on iOS is pretty straightforward. And dynamically loading an image into UIImageView can be achieved by many good extensions like SDWebImage . But how do you combine these two and display images asynchronously in an annotation? The answer is to customize MKAnnotationView. Custom MKAnnotationView You can extend MKAnnotationView in conjunction with SDWebImage. Here are the key parts of the custom class MKAnnotationView+WebCache.m:
#import "MKAnnotationView+WebCache.h" #import "SDWebImageManager.h" #import "SDImageCache.h" @implementation MKAnnotationView(WebCache) - (void)setImageWithURL:(NSURL *)url { [self setImageWithURL:url placeholderImage:nil]; } - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder { SDWebImageManager *manager = [SDWebImageManager sharedManager]; [manager cancelForDelegate:self]; [self setImage:placeholder]; if (url) { [manager downloadWithURL:url delegate:self]; } } - (void)cancelCurrentImageLoad { [[SDWebImageManager sharedManager] cancelForDelegate:self]; } - (void)webImageManager:(SDWebImageManager *)imageManager didFinishWithImage:(UIImage *)image { [self setImage:image]; } @end
Here is how you can use the above custom class in your project:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id )annotation { CustomAnnotation *anno = (CustomAnnotation *)annotation; static NSString *defaultPinID = @"customIdentifier"; MKAnnotationView *pinView = (MKAnnotationView *)[self.mapview dequeueReusableAnnotationViewWithIdentifier:defaultPinID]; if (pinView == nil) pinView = [[[MKAnnotationView alloc] initWithAnnotation:anno reuseIdentifier:defaultPinID] autorelease]; pinView.opaque = NO; pinView.canShowCallout = NO; pinView.draggable = NO; pinView.annotation = anno; NSURL *ImageURL = [NSURL URLWithString:IMAGE_URL_STRING]; [pinView setImageWithURL:ImageURL placeholderImage:[UIImage imageNamed:@"loading.png"]]; return pinView; }
You can download the complete source from github here PS::You can get updates of our work @mokriya and more sample projects from our github page















