Skip to content

Instantly share code, notes, and snippets.

@r-aamir
Last active February 2, 2019 10:45
Show Gist options
  • Save r-aamir/4d2fbc7c2d3f98682a57212b4543111b to your computer and use it in GitHub Desktop.
Save r-aamir/4d2fbc7c2d3f98682a57212b4543111b to your computer and use it in GitHub Desktop.
MKMapKit annotation clustering in Objective-C
#import <MapKit/MapKit.h>
@interface CustomAnnotationView : MKMarkerAnnotationView
- (id) initWithAnnotationWithImage:(id<MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier annotationViewImage:(UIImage *)annotViewImage;
@end
#import "CustomAnnotationView.h"
@implementation CustomAnnotationView
- (id) initWithAnnotationWithImage:(id<MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier annotationViewImage:(UIImage *)annotViewImage
{
self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
self.image = annotViewImage;
return self;
}
@end
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
@interface ViewController : UIViewController <MKMapViewDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@end
#import "ViewController.h"
#import "CustomAnnotationView.h"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.mapView setDelegate:self];
[self addDefaultAnnotations];
}
- (void)addDefaultAnnotations {
MKPointAnnotation *point1 = [[MKPointAnnotation alloc] init];
CLLocationCoordinate2D c1;
c1.latitude = 46.469391;
c1.longitude = 30.740883;
point1.coordinate = c1;
point1.title = @"Odessa, Ukraine";
[self.mapView addAnnotation:point1];
MKPointAnnotation *point2 = [[MKPointAnnotation alloc] init];
CLLocationCoordinate2D c2;
c2.latitude = 46.469391;
c2.longitude = 30.740883;
point2.coordinate = c2;
point2.title = @"Odessa, Ukraine";
[self.mapView addAnnotation:point2];
[_mapView setRegion:MKCoordinateRegionMakeWithDistance(c2, 500, 500) animated:YES];
}
#pragma mark - MKMapViewDelegate
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
if ([annotation isKindOfClass:[MKPointAnnotation class]]) {
CustomAnnotationView *annotationView = (CustomAnnotationView *) [self.mapView dequeueReusableAnnotationViewWithIdentifier:@"Jacky.S"];
if (annotationView == nil) {
annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"Jacky.S"];
annotationView.enabled = YES;
annotationView.clusteringIdentifier = @"pins";
// annotationView.glyphImage = [UIImage imageNamed:@"we can use a nice image instead of the default pins"];
} else {
annotationView.annotation = annotation;
annotationView.clusteringIdentifier = @"pins";
}
return annotationView;
}
return nil;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment