@interface MyCustomAnnotation : NSObject <MKAnnotation> { CLLocationCoordinate2D coordinate; } @property (nonatomic, readonly) CLLocationCoordinate2D coordinate; - (id)initWithLocation:(CLLocationCoordinate2D)coord; // Other methods and properties. @end @implementation MyCustomAnnotation @synthesize coordinate; - (id)initWithLocation:(CLLocationCoordinate2D)coord { self = [super init]; if (self) { coordinate = coord; } return self; } @end
MKAnnotationView* aView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"MyCustomAnnotation"] autorelease]; aView.image = [UIImage imageNamed:@"myimage.png"]; aView.centerOffset = CGPointMake(10, -20);
#import <UIKit/UIKit.h> #import <MapKit/MapKit.h> @interface MyCustomAnnotationView : MKAnnotationView { // Custom data members } // Custom properties and methods. @end Initializing a custom annotation view - (id)initWithAnnotation:(id <MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier { self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier]; if (self) { // Set the frame size to the appropriate values. CGRect myFrame = self.frame; myFrame.size.width = 40; myFrame.size.height = 40; self.frame = myFrame; // The opaque property is YES by default. Setting it to // NO allows map content to show through any unrendered // parts of your view. self.opaque = NO; } return self; }
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation { // If it's the user location, just return nil. if ([annotation isKindOfClass:[MKUserLocation class]]) return nil; // Handle any custom annotations. if ([annotation isKindOfClass:[MyCustomAnnotation class]]) { // Try to dequeue an existing pin view first. MKPinAnnotationView* pinView = (MKPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:@"CustomPinAnnotationView"]; if (!pinView) { // If an existing pin view was not available, create one. pinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"CustomPinAnnotation"] autorelease]; pinView.pinColor = MKPinAnnotationColorRed; pinView.animatesDrop = YES; pinView.canShowCallout = YES; // Add a detail disclosure button to the callout. UIButton* rightButton = [UIButton buttonWithType: UIButtonTypeDetailDisclosure]; [rightButton addTarget:self action:@selector(myShowDetailsMethod:) forControlEvents:UIControlEventTouchUpInside]; pinView.rightCalloutAccessoryView = rightButton; } else pinView.annotation = annotation; return pinView; } return nil; }