如何添加大頭針(地标):
通過MapView的addAnnotation方法可以添加一個大頭針到地圖上
通過MapView的addAnnotations方法可以添加多個大頭針到地圖上
–(void)addAnnotation:(id <MKAnnotation>)annotation;
說明:需要傳入一個遵守了MKAnnotation協定的對象
基本步驟為:
<1>建立一個遵守MKAnnotation協定的類:
@interface MyAnnotation : NSObject <MKAnnotation>
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;
@end
<2>添加Annotation:
MyAnnotation *anno = [[MyAnnotation alloc] init];
anno.title = @“中國";
anno.subtitle = @“北京”;
//經度和緯度
anno.coordinate = CLLocationCoordinate2DMake(40, 110);
//添加大頭針到地圖中
[_mapView addAnnotation:anno];
// 讓地圖挪動到對應的位置(經緯度交叉處)
[_mapView setCenterCoordinate:anno.coordinate animated:YES];
自定義大頭針:
實作MapView的代理方法
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
static NSString *ID = @"anno";
MKPinAnnotationView *annoView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:ID];
if (annoView == nil) {
annoView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:ID];
// 顯示氣泡
annoView.canShowCallout = YES;
// 設定綠色
annoView.pinColor = MKPinAnnotationColorGreen;
}
return annoView;
}
注意:可以通過設定MapAnnotationView的image屬性來自定義大頭針顯示的圖檔
涉及的幾個類一些屬性或方法的介紹:
//大頭針标注顔色枚舉
typedef NS_ENUM(NSUInteger, MKPinAnnotationColor) {
MKPinAnnotationColorRed = 0,
MKPinAnnotationColorGreen,
MKPinAnnotationColorPurple
} ;
//大頭針标注視圖類
@interface MKPinAnnotationView : MKAnnotationView
@property (nonatomic) MKPinAnnotationColor pinColor; //大頭針标注顔色
@property (nonatomic) BOOL animatesDrop; //是否顯示水滴動态
//标注視圖類
@interface MKAnnotationView : NSView
- (instancetype)initWithAnnotation:(id <MKAnnotation>)annotation reuseIdentifier:(NSString*)reuseIdentifier; //初始化
@property (nonatomic, readonly) NSString *reuseIdentifier; //重用标示符
@property (nonatomic, strong) id <MKAnnotation> annotation; //标注
@property (nonatomic, strong) UIImage *image; //圖像
@property (nonatomic) BOOL canShowCallout; //是否顯示氣泡
@property (strong, nonatomic) UIView *leftCalloutAccessoryView; //氣泡左視圖(多用來顯示圖檔)
@property (strong, nonatomic) UIView *rightCalloutAccessoryView; //氣泡右視圖(多用來顯示圖檔)
具體的示範執行個體如下:
功能:首先建立一個标注在地圖上顯示目前的區域的名字,然後建立一個長按手勢,當在人一個地點長按時,就會在長按的地方自動添加一個大頭針标注,并且會顯示一個氣泡顯示圖檔,地點名字資訊可以待定.........
前期準備:
1.導入Mapkit架構:

2.導入一個圖檔素材,用來做大頭針視圖的一個圖檔顯示:
3.自頂一個一個類,這個類實作了<MKAnnotation>協定,自定義類MyAnnotation截圖為:
代碼實作:
1.在自定義類的MYAnnotation.h檔案聲明大頭針标注的屬性
2、在ViewController.m檔案中聲明地圖視圖屬性,并實作地圖視圖的協定
3、給指定位置建立一個标注,同時建立長按手勢
4、處理長按手勢事件,建立自定義的大頭針标注
5、實作地圖視圖的代理方法
#pragma mark -mapView的代理方法
//顯示标注和氣泡,并在氣泡上設定圖檔
//選中标注和取消标注時調用的方法
示範結果:(選中和取消标注時,輸出結果就不列印了)
開始時: 點選大頭針标注時:
再随意在某一個地方長按時出現一個新的大頭這标注 點選大頭标注時:
程式猿神奇的手,每時每刻,這雙手都在改變着世界的互動方式!
本文轉自當天真遇到現實部落格園部落格,原文連結:http://www.cnblogs.com/XYQ-208910/p/4893349.html,如需轉載請自行聯系原作者