
在之前的使用 MapKit 取得目前地理位置與經緯度的設定文章中已經介紹過基本的MapView用法,這裡就不再重複,以下程式碼只有示範如何在 MapView 上加上註解說明的大頭針 Pin 。(View-based Template)
若用 Pin 則必須使用到 Framework 中的 MK Annotation Class,按照開發者文件說明,要使用此功能必須建立一個使用 MKAnnotation 的類別,並宣告該賴別三個屬性和一個初始化方法。(有興趣的讀者可以前往 iOS Library 中查詢更詳細的使用方式,並不一定要按照本篇j的方法設定)
PlacePin.h #import #import @interface PlacePin : NSObject { CLLocationCoordinate2D coordinate; NSString *title; NSString *subtitle; }
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate; @property (nonatomic, retain) NSString *title; @property (nonatomic, retain) NSString *subtitle; - (id)initWithCoordinate:(CLLocationCoordinate2D)coords; @end
PlacePin.m #import "PlacePin.h" @implementation PlacePin @synthesize coordinate, title, subtitle;
- (id)initWithCoordinate:(CLLocationCoordinate2D)coords { self = [super init]; if (self != nil) coordinate = coords;
return self; }
- (void) dealloc { [title release]; [subtitle release]; [super dealloc]; }
@end 在建立好 Class 之後,別忘記在專案中還要 #import 才能正常使用。下列程式碼將示範如何使用剛剛自行建立的 Class 來實做在 MapView 上加上註解說明的大頭針 Pin 。
//自行定義設定地圖標籤的函式 - (void)setViewMapPin { //宣告一個陣列來存放標籤 NSMutableArray *annotations = [[NSMutableArray alloc] init]; for (int i = 1; i <= 10; i++) { //隨機設定標籤的緯度 CLLocationCoordinate2D pinCenter; pinCenter.latitude = LATITUDE + (float)(arc4random() % 100) / 1000; pinCenter.longitude = LONGITUDE + (float)(arc4random() % 100) / 1000;
//建立一個地圖標籤並設定內文 PlacePin *annotation = [[PlacePin alloc]initWithCoordinate:pinCenter]; annotation.title = @"Furnace Digital"; annotation.subtitle = [NSString stringWithFormat:@"臨時作戰總部 - %i", i];
//將製作好的標籤放入陣列中 [annotations addObject:annotation]; [annotation release]; }
//將陣列中所有的標籤顯示在地圖上 [map addAnnotations:annotations]; [annotations release]; }
沒有留言:
張貼留言