user1179321
user1179321

Reputation: 801

Using a custom annotation when adding it to map

I'm having trouble accessing my custom annotation class when adding it to a mapview. I have the custom class working properly but i when i add it to the map i'm not sure how to access the custom annotation through this delegate:

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation

i've tried looking online and havent found anything. any help would be great.

Its called like this:

CLLocationCoordinate2D coords = CLLocationCoordinate2DMake(shops.latitude, shops.longitude);
    AnnotationForId *shop = [[AnnotationForId alloc] initWithCoordinate:coords];
    //[[CLLocationCoordinate2DMake(shops.latitude, shops.longtitude)]];
    shop.title = shops.name;
    shop.subtitle = @"Coffee Shop";
    shop.shopId = shops.id;
    [map addAnnotation:shop];

Upvotes: 0

Views: 757

Answers (2)

Lewis Gordon
Lewis Gordon

Reputation: 1731

Test the annotation to see if it's the same class as your custom class:

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    MKAnnotationView *mkav = nil;

    if ([annotation isKindOfClass:[AnnotationForId class]])
    {
        // This should be safe now.
        AnnotationForId *aid = annotation;
        // Whatever you wanted to add, including making your own view.
    }

    return mkav;
}

Upvotes: 0

iPatel
iPatel

Reputation: 47079

This is Simple Example For how to Create Custom AnnotationView.

Create custom AnnotationView:

#import <MapKit/MapKit.h>

@interface AnnotationView : MKPlacemark

@property (nonatomic, readwrite, assign) CLLocationCoordinate2D coordinate;

@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *subtitle;

// you can put here any controllers that you want. (such like UIImage, UIView,...etc)

@end

And in .m file

#import "AnnotationView.h"

@implementation AnnotationView

- (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate addressDictionary:(NSDictionary *)addressDictionary
{
    if ((self = [super initWithCoordinate:coordinate addressDictionary:addressDictionary]))
    {
        self.coordinate = coordinate;
    }
    return self;
}

@end

// Use Annotation Add #import "AnnotationView.h" in your relevant .m file:

CLLocationCoordinate2D pCoordinate ;
pCoordinate.latitude = LatValue;
pCoordinate.longitude = LanValue;

// Create Obj Of  AnnotationView class  

AnnotationView *annotation = [[AnnotationView alloc] initWithCoordinate:pCoordinate addressDictionary:nil] ;

    annotation.title = @"I m Here";
    annotation.subtitle = @"This is Sub Tiitle";

[self.mapView addAnnotation:annotation];

Upvotes: 1

Related Questions