簡體   English   中英

將自定義注釋添加到地圖時使用

[英]Using a custom annotation when adding it to map

將我的自定義注釋類添加到mapview時,無法訪問它。 我的自定義類工作正常,但是當我將其添加到地圖時,我不確定如何通過此委托訪問自定義注釋:

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

我嘗試過在線尋找,還沒有發現任何東西。 任何幫助都會很棒。

其調用方式如下:

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

這是有關如何創建自定義AnnotationView的簡單示例。

創建自定義的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

並在.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

//使用注釋在相關的.m file添加#import "AnnotationView.h"

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

測試注釋以查看它是否與您的自定義類相同:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM