要取得當前位置資訊,除了用 CoreLocation 的 CLLocation 系列之外,也可以搭配 MapKit。個人認為在需要更精確位置資訊的場合,MapKit 這條路更有用,而且使用上相當方便。
先建立位置管理器實例並設定 delegate,然後呼叫 startUpdatingLocation。系統會透過委派持續回報座標:
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
CLLocationDistance l = newLocation.coordinate.latitude; // 緯度
CLLocationDistance v = newLocation.coordinate.longitude; // 經度
NSLog(@"%f %f", l, v);
// 計算與另一座標之間的距離(公尺)
CLLocation *new = [[CLLocation alloc] initWithLatitude:11.0 longitude:12.0];
CLLocationDistance u = [newLocation distanceFromLocation:new];
NSLog(@"%f", u);
[self startedReverseGeoderWithLatitude:l longitude:v];
}
這裡要更正一個常見的混淆:latitude 是緯度、longitude 是經度。原範例的註解把兩者寫反了。記憶方法是 latitude 與 ladder(梯子)同源,梯子橫放就是緯線;longitude 則與 longitude line(經線)對應。
另外,CLLocationDistance 其實只是 double 的別名,用來表示公尺數。用它來承接「度數」的座標值語意上並不精確,宣告成 CLLocationDegrees 或直接 double 更合適。
有了座標,接著反查它對應的城市、街道等地名。做法是建立 MKReverseGeocoder 並以座標初始化:
- (void)startedReverseGeoderWithLatitude:(double)latitude
longitude:(double)longitude {
CLLocationCoordinate2D coordinate2D;
coordinate2D.longitude = longitude;
coordinate2D.latitude = latitude;
MKReverseGeocoder *geoCoder = [[MKReverseGeocoder alloc] initWithCoordinate:coordinate2D];
geoCoder.delegate = self;
[geoCoder start];
}
#pragma mark -
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder
didFindPlacemark:(MKPlacemark *)placemark {
NSLog(@"當前城市:%@", placemark.locality);
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder
didFailWithError:(NSError *)error {
NSLog(@"MKReverseGeocoder has failed.");
}
流程是:用當前經緯度初始化 geocoder,設定 delegate,呼叫 start,然後在 didFindPlacemark 中從 MKPlacemark 取出需要的欄位。MKPlacemark 提供的資訊相當豐富,除了 locality(城市),還有 thoroughfare(街道)、subThoroughfare(門牌)、administrativeArea(州/省)、country(國家)、postalCode(郵遞區號)、ISOcountryCode 等,可依需求取用。
一、反查需要網路,且有速率限制。這個服務會向蘋果的伺服器查詢,離線時必然失敗;同時蘋果明確規定同一個 App 生命週期內最多只能發出 50 次請求,超過就會開始收到錯誤。因此千萬別在 didUpdateToLocation 中無條件呼叫——位置更新是持續觸發的,這樣寫幾秒之內就會用完額度。正確做法是加上節流判斷,例如只在移動距離超過數百公尺時才反查一次。
二、MKReverseGeocoder 自 iOS 5 起已被廢棄。官方替代方案是 CLGeocoder:
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
[geocoder reverseGeocodeLocation:location
completionHandler:^(NSArray *placemarks, NSError *error) {
if (error == nil && [placemarks count] > 0) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(@"當前城市:%@", placemark.locality);
}
}];
CLGeocoder 使用 block 回呼,不必實作委派方法,程式碼更集中;而且它同時支援正向地理編碼(地名轉座標)。新專案請一律使用 CLGeocoder。
三、别忘了要求權限與處理拒絕。使用前必須先呼叫 requestWhenInUseAuthorization(或 requestAlwaysAuthorization),並在 Info.plist 中設定 NSLocationWhenInUseUsageDescription 說明用途,否則 App 會直接崩潰。同时要實作 locationManager:didChangeAuthorizationStatus:,在使用者拒絕時給出引導,而不是讓程式安靜地永遠收不到位置。
四、didUpdateToLocation 中的 oldLocation 可以拿來過濾雜訊。接收器初期常會回報精度很差的粗定位,判斷 newLocation.horizontalAccuracy < 0 或與 oldLocation 距離過小就忽略,能有效避免 UI 上的位置標記四處跳動。