使用者輸入一段地址,App 要換成座標才能在地圖上打點或做距離計算,這就是「地理編碼」(geocoding)的工作。iOS 內建的 CLGeocoder 包裝得相當完整,一行呼叫就能完成。
CLGeocoder *myGeocoder = [[CLGeocoder alloc] init];
[myGeocoder geocodeAddressString:_searchBar.text completionHandler:^(NSArray *placemarks, NSError *error) {
if ([placemarks count] > 0 && error == nil) {
CLPlacemark *firstPlacemark = [placemarks objectAtIndex:0];
NSLog(@"latitude: %f", firstPlacemark.location.coordinate.latitude);
NSLog(@"longitude: %f", firstPlacemark.location.coordinate.longitude);
}
else if ([placemarks count] == 0 && error == nil) {
NSLog(@"找不到對應的地標");
}
else if (error != nil) {
NSLog(@"發生錯誤:%@", error);
}
}];
上面的程式碼刻意分成三個分支,這不是囉嗦,而是三種完全不同的狀況:
特別要注意的是,Apple 對地理編碼服務有速率限制。若短時間內送出大量請求,會收到 kBGeocoderErrorNetWorkFailure 這類錯誤,實務上必須節流。
CLGeocoder 走的是 Apple 的地圖服務,辨識能力會隨 locale 而異。若使用者系統語言與輸入地址的語言不同,命中率會下降。可以改用 geocodeAddressString:region:completionHandler: 搭配 region 參數(例如指定台灣或中國大陸範圍)來提高準確度。
// 簡單的節流:同一段文字在短時間內不重複送出
static NSString *lastQuery = nil;
static NSTimeStamp lastTime = 0;
if ([lastQuery isEqualToString:_searchBar.text] && (CACurrentMediaTime() - lastTime) < 1.0) {
return; // 使用者還在打字,跳過這次請求
}
lastQuery = [_searchBar.text copy];
lastTime = CACurrentMediaTime();
Apple 建議每完成一次編碼就重新建立 CLGeocoder,或至少不要在多個併行請求間共用同一個實例,否則容易出現回呼被合併或取消的怪異行為。
如果需求相反,用 reverseGeocodeLocation:completionHandler:,傳入 CLLocation 即可取得 CLPlacemark,其中 thoroughfare(街道)、locality(城市)、administrativeArea(行政區)、country(國家)等欄位可以組出完整的可讀地址。
若後續會用到使用者當前位置,別忘了在 Info.plist 中補上 NSLocationWhenInUseUsageDescription,並在 CLLocationManager 中請求授權,否則 iOS 會直接拒絕提供座標。