智慧型手機普及之後,愈來愈多生活瑣事被搬進 App:臨時要去一個陌生地址、想找附近的餐廳或電影院、順路查最近的銀行與飯店。這些場景背後其實都繞著兩個問題打轉——「我現在在哪裡」以及「我要去哪裡」。
在 iOS 平台上想實現這類功能,通常得搭配兩個系統框架:
另外記兩個業界常用術語:LBS(Location Based Service,基於位置的服務)與 SoLoMo(Social、Local、Mobile 三者結合的產品思維)。
先在專案設定中把 CoreLocation.framework 加入依賴;Xcode 5 之後已不必手動勾選,編譯器會自動連結。接著在需要使用的地方引入主標頭檔:
#import <CoreLocation/CoreLocation.h>

Core Location 內所有型別的前綴都是 CL,看到 CLLocation、CLGeocoder、CLPlacemark 就能立刻認出同系列;而真正負責取得定位的是 CLLocationManager 物件。

經度以通過英國倫敦格林 CONDITIONS 天文台的本初子午線為零度:向東為東經(E),向西為西經(W),各 180°,合計 360°。
緯度以赤道為零度:向北為北緯(N),向南為南緯(S),各 90°,合計 180°。
實務上要注意:跨經緯度的度數越大(1° 約 111 公里),代表地圖涵蓋的範圍越廣,畫面上的地物看起來就越小。
我國的經緯度範圍大致為:緯度 N 3°51′ ~ N 53°33′,經度 E 73°33′ ~ E 135°05′。

撰寫與除錯階段不可能真的抱著裝置跑遍各地,Xcode 內建的模擬位置功能就能解決這個問題:執行時指定一組經緯度,App 收到的座標就會是該處。


CLGeocoder 是 Core Location 提供的編碼器(Geo 取自 Geography)。它同時包辦兩件事:
- (void)geocodeAddressString:(NSString *)addressString
completionHandler:(CLGeocodeCompletionHandler)completionHandler;
- (void)reverseGeocodeLocation:(CLLocation *)location
completionHandler:(CLGeocodeCompletionHandler)completionHandler;
兩個介面共用同一個 completion block(CLGeocodeCompletionHandler),無論成功或失敗都會被呼叫,並帶回兩個參數:error 在查無結果或請求失敗時有值;placemarks 則是裝著 CLPlacemark 的陣列。

CLPlacemark 就是「地標」物件,把地址的各個層級都封裝好了,常用的屬性包含:
@property (nonatomic, readonly) CLLocation *location; // 地理座標 @property (nonatomic, readonly) CLRegion *region; // 所屬區域 @property (nonatomic, readonly) NSDictionary *addressDictionary;// 完整地址字典 @property (nonatomic, readonly) NSString *name; // 地址名稱 @property (nonatomic, readonly) NSString *locality; // 城市
先用 storyboard 搭出介面:上方一組輸入框與標籤負責地理編碼,下方一組負責反地理編碼。

#import "YYViewController.h"
#import <CoreLocation/CoreLocation.h>
@interface YYViewController ()
@property (nonatomic, strong) CLGeocoder *geocoder;
// 地理編碼
- (IBAction)geocode;
@property (weak, nonatomic) IBOutlet UITextField *addressField;
@property (weak, nonatomic) IBOutlet UILabel *longitudeLabel;
@property (weak, nonatomic) IBOutlet UILabel *latitudeLabel;
@property (weak, nonatomic) IBOutlet UILabel *detailAddressLabel;
// 反地理編碼
- (IBAction)reverseGeocode;
@property (weak, nonatomic) IBOutlet UITextField *longitudeField;
@property (weak, nonatomic) IBOutlet UITextField *latitudeField;
@property (weak, nonatomic) IBOutlet UILabel *reverdeDetailAddressLabel;
@end
@implementation YYViewController
#pragma mark - 懶載入
- (CLGeocoder *)geocoder {
if (_geocoder == nil) {
_geocoder = [[CLGeocoder alloc] init];
}
return _geocoder;
}
- (void)viewDidLoad {
[super viewDidLoad];
}
#pragma mark - 地理編碼:地名 -> 座標
- (IBAction)geocode {
NSString *address = self.addressField.text;
if (address.length == 0) return;
[self.geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {
if (error || placemarks.count == 0) {
self.detailAddressLabel.text = @"查無此地,你確定不是寫到月球去了?";
return;
}
for (CLPlacemark *pm in placemarks) {
NSLog(@"name=%@ locality=%@ country=%@ postalCode=%@",
pm.name, pm.locality, pm.country, pm.postalCode);
}
CLPlacemark *first = [placemarks firstObject];
self.detailAddressLabel.text = first.name;
CLLocationDegrees latitude = first.location.coordinate.latitude;
CLLocationDegrees longitude = first.location.coordinate.longitude;
self.latitudeLabel.text = [NSString stringWithFormat:@"%.2f", latitude];
self.longitudeLabel.text = [NSString stringWithFormat:@"%.2f", longitude];
}];
}
#pragma mark - 反地理編碼:座標 -> 地名
- (IBAction)reverseGeocode {
NSString *longitudeText = self.longitudeField.text;
NSString *latitudeText = self.latitudeField.text;
if (longitudeText.length == 0 || latitudeText.length == 0) return;
CLLocationDegrees latitude = [latitudeText doubleValue];
CLLocationDegrees longitude = [longitudeText doubleValue];
CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
[self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
if (error || placemarks.count == 0) {
self.reverdeDetailAddressLabel.text = @"查無此地,你確定不是寫到月球去了?";
return;
}
CLPlacemark *first = [placemarks firstObject];
self.reverdeDetailAddressLabel.text = first.name;
self.latitudeField.text = [NSString stringWithFormat:@"%.2f", first.location.coordinate.latitude];
self.longitudeField.text = [NSString stringWithFormat:@"%.2f", first.location.coordinate.longitude];
}];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.view endEditing:YES];
}
@end
地理編碼(地名 → 座標)

主控台會把找到的所有地標欄位都印出來,方便確認解析結果。

反地理編碼(座標 → 地名)

鍵盤處理

經緯度欄位建議把鍵盤型別設為數字鍵盤,並在點擊空白處時呼叫 endEditing: 收合鍵盤。

最後一點常被忽略:在中國境內,Apple 的地圖與地理編碼服務由第三方供應商提供,因此查詢結果僅涵蓋境內範圍,邊界地帶的地址可能會有偏差。