Using a custom annotation when adding it to map

两盒软妹~` 提交于 2019-11-28 12:13:17

问题


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];

回答1:


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];



回答2:


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;
}


来源:https://stackoverflow.com/questions/15684080/using-a-custom-annotation-when-adding-it-to-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!