行動裝置上,地圖與定位幾乎是所有生活類應用的基礎能力:導航帶你去陌生的地方,周邊服務幫你找餐館、酒店、銀行、電影院。在 iOS 上實作這些功能,離不開兩個框架——Core Location 負責地理定位,Map Kit 負責地圖展示。
順帶記兩個常見術語:LBS 是 Location Based Service(位置服務)的縮寫;SoLoMo 指 Social + Local + Mobile,這個組合詞正是描述當前行動應用的核心特徵。
使用前必須先匯入框架與主標頭檔:
#import <CoreLocation/CoreLocation.h>
有個容易記的慣例:CoreLocation 框架中所有資料型別的前綴都是 CL,看到 CL 開頭就知道來自這個框架。
用戶定位由 CLLocationManager 物件負責,最基本的一對方法就是開始與停止:
- (void)startUpdatingLocation; - (void)stopUpdatingLocation;
呼叫 startUpdatingLocation 之後,系統會持續定位,並頻繁回呼代理方法:
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations;
locations 參數裡裝的就是 CLLocation 物件。及時在不需要時呼叫 stopUpdatingLocation,是節電的基本禮儀。
@property(readonly, nonatomic) CLLocationCoordinate2D coordinate; // 經緯度 @property(readonly, nonatomic) CLLocationDistance altitude; // 海拔 @property(readonly, nonatomic) CLLocationDirection course; // 航向,0.0°~359.9°,0 代表真北 @property(readonly, nonatomic) CLLocationSpeed speed; // 速度,單位 m/s
計算兩點之間的距離:
- (CLLocationDistance)distanceFromLocation:(const CLLocation *)location;
兩個影響定位行為的關鍵屬性:
@property(assign, nonatomic) CLLocationDistance distanceFilter; // 每移動多少公尺才回報一次 @property(assign, nonatomic) CLLocationAccuracy desiredAccuracy; // 精度,越精確越耗電
typedef struct {
CLLocationDegrees latitude; // 緯度
CLLocationDegrees longitude; // 經度
} CLLocationCoordinate2D;
// 一般透過此函數建立
CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(39.9, 116.4);
在模擬器上測試時,記得於 Xcode 手動設定模擬位置,否則不會有真實座標回傳。
從 iOS 6 開始,蘋果大幅加強了使用者隱私保護。取得用戶位置、存取通訊錄、日曆、相機、相簿等行為,都必須先取得授權。當 App 嘗試存取隱私資訊時,系統會自動彈出對話框詢問。
開發者可在 Info.plist 中設定 NSLocationUsageDescription(Privacy - Location Usage Description),用一段話說明定位的目的。這段文字会直接呈現在系統的授權提示中,值得認真撰寫。
一旦使用者選擇「Don't Allow」,你的應用此後就無法再使用定位功能。因此嚴謹的做法是在使用定位前先判斷服務是否可用:
+ (BOOL)locationServicesEnabled; // 注意:此為舊版 API 名稱
CLGeocoder 負責兩個方向的轉換:
地理編碼(geocode):由地名取得具體位置資訊,例如經緯度、完整地址。
反地理編碼(reverse geocode):由經緯度取得具體位置資訊。
- (void)geocodeAddressString:(NSString *)addressString
completionHandler:(CLGeocodeCompletionHandler)completionHandler;
- (void)reverseGeocodeLocation:(CLLocation *)location
completionHandler:(CLGeocodeCompletionHandler)completionHandler;
typedef void (^CLGeocodeCompletionHandler)(NSArray *placemarks, NSError *error);
完成時回呼的 block 帶兩個參數:error 在編碼失敗時有值;placemarks 裡裝的是 CLPlacemark 物件。
@property (nonatomic, readonly) CLLocation *location; // 地理位置 @property (nonatomic, readonly) CLRegion *region; // 區域 @property (nonatomic, readonly) NSDictionary *addressDictionary;// 完整地址(key 為 kABPersonAddress*) @property (nonatomic, readonly) NSString *name; // 地址名稱 @property (nonatomic, readonly) NSString *locality; // 城市
#import <MapKit/MapKit.h>
同樣的慣例:MapKit 中所有型別前綴為 MK。最重要的 UI 控件是 MKMapView,專門用於地圖顯示。
// 地圖樣式 MKMapTypeStandard // 普通地圖 MKMapTypeSatellite // 衛星星空圖 MKMapTypeHybrid // 普通地圖疊加於衛星圖之上 // 使用者位置追蹤模式 MKUserTrackingModeNone // 不追蹤 MKUserTrackingModeFollow // 追蹤並顯示當前位置 MKUserTrackingModeFollowWithHeading // 追蹤並讓地圖隨前進方向旋轉
// 使用者位置更新,呼叫頻繁 - (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation; // 顯示區域即將改變 / 已經改變 - (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated; - (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated;
@property (nonatomic, copy) NSString *title; // 大頭針標題 @property (nonatomic, copy) NSString *subtitle; // 子標題 @property (readonly, nonatomic) CLLocation *location;
// 中心點
@property (nonatomic) CLLocationCoordinate2D centerCoordinate;
- (void)setCenterCoordinate:(CLLocationCoordinate2D)coordinate animated:(BOOL)animated;
// 顯示區域
@property (nonatomic) MKCoordinateRegion region;
- (void)setRegion:(MKCoordinateRegion)region animated:(BOOL)animated;
typedef struct {
CLLocationCoordinate2D center; // 中心點
MKCoordinateSpan span; // 跨度
} MKCoordinateRegion;
typedef struct {
CLLocationDegrees latitudeDelta; // 緯度跨度
CLLocationDegrees longitudeDelta; // 經度跨度
} MKCoordinateSpan;
- (void)addAnnotation:(id <MKAnnotation>)annotation; - (void)addAnnotations:(NSArray *)annotations; - (void)removeAnnotation:(id <MKAnnotation>)annotation; - (void)removeAnnotations:(NSArray *)annotations;
參數型別 id <MKAnnotation> 指的是大頭針模型物件,用來封裝座標、標題、子標題等資料。自訂一個模型類只要遵循 MKAnnotation 協議即可:
#import <MapKit/MapKit.h> @interface CustomAnnotation : NSObject <MKAnnotation> @property (nonatomic, assign) CLLocationCoordinate2D coordinate; // 必備 @property (nonatomic, copy) NSString *title; @property (nonatomic, copy) NSString *subtitle; @end // 使用 CustomAnnotation *anno = [[CustomAnnotation alloc] init]; anno.title = @"title"; anno.subtitle = @"subtitle"; anno.coordinate = CLLocationCoordinate2DMake(40, 116); [self.mapView addAnnotation:anno];
做法是設定 MKMapView 的代理,並實作以下方法回傳大頭針控件:
- (MKAnnotationView *)mapView:(MKMapView *)mapView
viewForAnnotation:(id <MKAnnotation>)annotation {
// 系統的藍色光點也走同一個代理,必須先分辨型別
if (![annotation isKindOfClass:[CustomAnnotation class]]) return nil;
static NSString *ID = @"tuangou";
MKAnnotationView *annoView = [mapView dequeueReusableAnnotationViewWithIdentifier:ID];
if (annoView == nil) {
annoView = [[MKAnnotationView alloc] initWithAnnotation:annotation
reuseIdentifier:ID];
annoView.canShowCallout = YES;
}
annoView.annotation = annotation;
annoView.image = [UIImage imageNamed:((CustomAnnotation *)annotation).icon];
return annoView;
}
兩個實務要點:回傳 nil 時會採用系統預設樣式;標示使用者位置的藍色發光圓點本身也是一個大頭針,因此務必在代理中判斷 annotation 的實際型別,否則自訂樣式會套用到光點上。
@property (nonatomic, strong) id <MKAnnotation> annotation; // 關聯的模型 @property (nonatomic, strong) UIImage *image; // 顯示圖片 @property (nonatomic) BOOL canShowCallout; // 是否顯示氣泡標注 @property (nonatomic) CGPoint calloutOffset; // 標注偏移量 @property (strong, nonatomic) UIView *rightCalloutAccessoryView; @property (strong, nonatomic) UIView *leftCalloutAccessoryView;
其子類 MKPinAnnotationView 專門呈現系統風格的水滴針,多了兩個屬性:
@property (nonatomic) MKPinAnnotationColor pinColor; // 針的顏色(紅、綠、紫) @property (nonatomic) BOOL animatesDrop; // 首次顯示是否落下動畫
關於自定義大頭針,以及點擊後彈出對應說明 view 的互動細節,還有相當多眉角可以處理,這裡先整理到骨架層次。把上述流程串起來,一個具備定位、顯示、標記能力的地圖頁面就能完整跑起來了。