iOS MKAnnotation協議爲地圖添加註解

添加地圖註解,這個需要用到MKAnnotation這個協議,主要有兩個UILabel類型的屬性,title和subtitle,當用戶點擊小別針時候就會把相關信息顯示出來,如下圖:
Google地圖實現之三添加註解 - tergol - tergol的博客
 
大概的操作是這樣的,先定義一個繼承了MKAnnotation的類,第當需要加上註解的時候,就根據當前的region等信息,實例化出一個對像,然後把它addAnnotation到googleMap上去就可了。
爲了實現MKAnnotation我們重新定義一個類來操作。新建objectiv-c的NSObject類
.h頭文件
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h> 
#import <MapKit/MapKit.h> 
@interface MapAnnotations : NSObject <MKAnnotation>{
CLLocationCoordinate2D coordinate;//這個表示一點,在map中就是中心點。
  NSString *subtitle; 
  NSString *title; 
}
-(id)initWithCoordinate:(CLLocationCoordinate2D) coordinate;
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic, retain) NSString *subtitle; 
@property (nonatomic, retain) NSString *title; 
@end
.m源文件
#import "MapAnnotations.h"
@implementation MapAnnotations
@synthesize coordinate;
@synthesize title;
@synthesize subtitle;
-(id)initWithCoordinate:(CLLocationCoordinate2D) c{
coordinate=c;
NSLog(@"%f,%f",c.latitude,c.longitude);
return self;
}
- (void) dealloc  
{
[title release];
[subtitle release];
[super dealloc];
}
@end
好了,有了這個類,我們就可以在數據更新的地方,實例化它的對像,然後加在MKMapview的實例上,就可以了,如下:
mapAnnotations=[[MapAnnotations alloc] initWithCoordinate:loc];
mapAnnotations.title=@"TEST";
mapAnnotations.subtitle=@"have a try";
[map addAnnotation:mapAnnotations];
[mapAnnotations release];

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章