MKMapView提供了一套可植入的地圖介面,可以讓我們在應用中展示地圖,並對其進行相關的操作。一般來說,我們可以指定一個展示地區,放一些標記在上面,還可以加蓋一些層在上面。
MKMapView依賴Google map裡面相關服務(如Google Earth API等),所以地圖的左下角會有Google字樣。
使用:
1.MKMapView的顯示
(1)建立MKMapView
CGRect rect = CGRectMake(0, 0, 320, 460); MKMapView *mapView = [[MKMapView alloc] initWithFrame:rect]; //定義經緯度 CLLocationCoordinate2D theCoordinate; theCoordinate.latitude=22.5414; //緯度 theCoordinate.longitude=113.946; //經度 //定義顯示範圍 MKCoordinateSpan theSpan; theSpan.latitudeDelta=0.01; theSpan.longitudeDelta=0.01; //定義一個地區(使用設定的經度緯度加上一個範圍) MKCoordinateRegion theRegion; theRegion.center=theCoordinate; theRegion.span=theSpan; //設定地圖顯示類型:[mapViewsetMapType:MKMapTypeStandard];
//將mapview的顯示地區設定為theRegion [mapView setRegion:theRegion];
對於mapType,在MKTypes裡有這樣一段字典定義:
enum { MKMapTypeStandard, MKMapTypeSatellite, MKMapTypeHybrid};typedef NSUInteger MKMapType;standard:標註地圖,顯示街道和街道名
Satellite:衛星圖片區
Hybrid:衛星圖,同時在相應地區有標註了街道和街道名
2.在MKMapView上添加標註
(1)和標註相關的類及協議
*MKAnnotation Protocol
標註必須實現這個協議,有三個屬性,coordinate,title和subtitle,其中coordinate屬性必須設定。
*MKAnnotationView
設定好Annotation後就可以用這個把標註在地圖上顯示出來,
-(id)initWithAnnotation:(id<MKAnnotation>)annotationreuseIdentifier:(NSString *)reuseIdentifier
其比較重要的屬性有
@property(nonatomic, retain) UIImage *image
自訂在地圖上標註的圖片
@property(nonatomic) BOOL canShowCallout
設定點擊後能否彈出標註
@property (retain,nonatomic) UIView *rightCalloutAccessoryView
property (retain,nonatomic) UIView *leftCalloutAccessoryView
設定在標註的左右邊點擊後進一步彈出附屬的View
*MKPinAnnotationView
這是提供的圖釘方式顯示標註,繼承自MKAnnotationView,添加了兩個屬性
@property(nonatomic) MKPinAnnotationColor pinColor
設定圖釘的顏色,有紅綠紫三種顏色可選擇
@property(nonatomic) BOOL animatesDrop
設定圖釘是否以掉下來的動畫方式顯示
(2)在地圖上添加Annotation的步驟
1》建立一個實現MKAnnotation協議的類,在該類的初始化函數中給其coordinate屬性設定
2》用上述方法建立Annotation
3》把建立的Annotation用addAnnotation的方法添加到MapView中
4》實現MKMapViewDelegate代理,在代理函數
- (MKAnnotationView*)mapView:(MKMapView *)mView viewForAnnotation:(id<MKAnnotation>)annotation中把Annotation變成MKAnnotationView返回,然後會在在地圖上上顯示。
3.在MKMapView上添加overLays
overLay是mapView的另一大功能,如annotation類似,MKMapView也維護著一個overLays的隊列,overLay就是在地圖上式覆蓋某種形式的視圖,如公交線路圖,包括線路上各停靠站等,overLay必須實現協議MKOverlay,同時必須指定其形狀,大小,以及在地圖上的定位,與Annotation一樣,它也不能獨立展現在地圖上,它的展示由MKOverlayView來管理(如同annotation的展示由MKAnnotationView來管理),然後使用add/insertOverlay相關的函數添加到mapView裡面就可以了。
(代碼稍後補上)