做專案時常會用到地圖,例如在圖上標示附近的人、在微博客戶端顯示附近的貼文等。因此有必要認識 MKMapView 這個類別,它繼承自 UIView。
@property(nonatomic) MKMapType mapType; // 地圖類型 // MKMapTypeStandard 標準地圖 // MKMapTypeSatellite 衛星視圖 // MKMapTypeHybrid 混合顯示 @property(nonatomic, getter=isZoomEnabled) BOOL zoomEnabled; // 是否可用捏合縮放 @property(nonatomic, getter=isScrollEnabled) BOOL scrollEnabled; // 是否可滑動 @property(nonatomic, assign) id<MKMapViewDelegate> delegate; // 代理 @property(nonatomic) MKCoordinateRegion region; // 當前顯示區域 @property(nonatomic) CLLocationCoordinate2D centerCoordinate; // 中心座標 @property(nonatomic) BOOL showsUserLocation; // 是否顯示使用者位置 @property(nonatomic, readonly) MKUserLocation *userLocation; // 使用者位置註釋 @property(nonatomic, readonly) NSArray *annotations; // 註釋列表(大頭針) @property(nonatomic) MKUserTrackingMode userTrackingMode; // 跟蹤模式
其中 MKCoordinateRegion 由 center(區域中心)與 span(經緯度跨度,即縮放級別)組成;userTrackingMode 則有 None(不跟蹤)、Follow(跟隨移動)、FollowWithHeading(跟隨並隨方向旋轉)三種。
// 操作可視區域 - (void)setRegion:(MKCoordinateRegion)region animated:(BOOL)animated; - (void)setCenterCoordinate:(CLLocationCoordinate2D)coordinate animated:(BOOL)animated; - (void)setVisibleMapRect:(MKMapRect)mapRect animated:(BOOL)animate; // 註釋管理 - (void)addAnnotation:(id<MKAnnotation>)annotation; - (void)addAnnotations:(NSArray *)annotations; - (void)removeAnnotation:(id<MKAnnotation>)annotation; - (MKAnnotationView *)dequeueReusableAnnotationViewWithIdentifier:(NSString *)identifier; // 選擇註釋 - (void)selectAnnotation:(id<MKAnnotation>)annotation animated:(BOOL)animated; - (void)deselectAnnotation:(id<MKAnnotation>)annotation animated:(BOOL)animated; // 覆蓋層管理 - (void)addOverlay:(id<MKOverlay>)overlay; - (void)insertOverlay:(id<MKOverlay>)overlay aboveOverlay:(id<MKOverlay>)sibling; - (void)exchangeOverlayAtIndex:(NSUInteger)index1 withOverlayAtIndex:(NSUInteger)index2;
- (CGPoint)convertCoordinate:(CLLocationCoordinate2D)coordinate toPointToView:(UIView *)view; - (CLLocationCoordinate2D)convertPoint:(CGPoint)point toCoordinateFromView:(UIView *)view; - (CGRect)convertRegion:(MKCoordinateRegion)region toRectToView:(UIView *)view;
这些方法实现了現實世界經緯度與視圖座標之間的相互轉換,還可透過 regionThatFits: 與 mapRectThatFits: 調整區域比例以適應地圖框架,並以 setUserTrackingMode:animated: 設定跟蹤模式。以上是 MKMapView 的整體輪廓,若有不精準之處還請指正——LC。