現在的手機應用幾乎都離不開定位:叫車、找附近的人、找附近的餐廳,全都需要 CoreLocation 與 MapKit。
先記一個很多人會搞混的觀念:我們平常說「東經西經」,經線是與赤道平行、包含赤道線的那一組;而從南極連到北極的是緯線。把這句話記住就不容易再弄反。
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
[CLLocationManager locationServicesEnabled] // 回傳 Bool
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
可用的精度等級由高到低:
locationManager.distanceFilter = 50; // 移動超過 50 公尺才通知 delegate
更新太頻繁會耗電。如果你希望每次有變化就回報,可以設成 kCLDistanceFilterNone,也就是不做篩選。
[locationManager requestWhenInUseAuthorization]; // App 在前台時可定位
[locationManager requestAlwaysAuthorization]; // 持續可定位
同時要在 Info.plist 裡補上 NSLocationWhenInUseUsageDescription 或 NSLocationAlwaysUsageDescription,否則授權彈窗根本不會出現。
[locationManager startUpdatingLocation];
[locationManager stopUpdatingLocation];
記得遵循 CLLocationManagerDelegate 協議並實作 didUpdateLocations。用完就 stop,否則 App 打開期間會一直定位。
struct MKCoordinateSpan {
CLLocationDegrees latitudeDelta; // double
CLLocationDegrees longitudeDelta;
};
struct MKCoordinateRegion {
CLLocationCoordinate2D center; // 畫面中心
MKCoordinateSpan span; // 顯示比例
};
方向感的部分用 startUpdatingHeading 與 stopUpdatingHeading 控制。
經緯度沒辦法直接告訴使用者「你在台北車站」,這時需要 CLGeocoder。
geocodeAddressString(_:completionHandler:)
geocodeAddressString(_:inRegion:completionHandler:)
reverseGeocodeLocation(_:completionHandler:)
查詢結果是一個 CLPlacemark 物件,裡面才有城市、路名、郵遞區號這些人類看得懂的欄位。
iOS 地圖開發有兩條路:使用 MapKit 框架,或直接開啟系統地圖 App。後者無法精細控制,重點還是 MapKit。
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView?
func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView)
以上內容整理自公開資源與官方文件,實際串接時建議搭配 CLGeocoder 的錯誤處理,因為網路不良或超出查詢配額時它會回傳 error。