利用 MKReverseGeocoder(iOS 5.0 棄用,現推薦 CLGeocoder)將經緯度轉換為人類可讀地址,是 LBS 應用的基礎能力。
- (void)reverseGeocodeCoordinate:(CLLocationCoordinate2D)coordinate {
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
CLLocation *location = [[CLLocation alloc] initWithLatitude:coordinate.latitude
longitude:coordinate.longitude];
[geocoder reverseGeocodeLocation:location
completionHandler:^(NSArray * _Nullable placemarks,
NSError * _Nullable error) {
if (error) {
NSLog(@"反地理編碼失敗: %@", error.localizedDescription);
return;
}
CLPlacemark *placemark = placemarks.firstObject;
if (placemark) {
[self parsePlacemark:placemark];
}
}];
}
| 屬性 | 含義 | 示例 |
|---|---|---|
name | 地標名稱 | 「騰訊大廈」 |
thoroughfare | 街道名 | 「科韻路」 |
subThoroughfare | 門牌號 | 「18號」 |
locality | 城市 | 「廣州市」 |
subLocality | 區/縣 | 「天河區」 |
administrativeArea | 省/直轄市 | 「廣東省」 |
postalCode | 郵政編碼 | 「510000」 |
country | 國家 | 「中國」 |
countryCode | 國家代碼 | 「CN」 |
addressDictionary | 完整地址字典(含格式化數組) | 見下文 |
{
City = "廣州市";
Country = "中國";
CountryCode = CN;
FormattedAddressLines = (
"中國",
"廣東省廣州市天河區",
"科韻路18號"
);
State = "廣東省";
Street = "科韻路18號";
SubLocality = "天河區";
SubThoroughfare = "18號";
Thoroughfare = "科韻路";
}
kCLErrorNetwork,需指數退避重試。preferredLocale。Info.plist 必須包含 NSLocationWhenInUseUsageDescription 或 NSLocationAlwaysUsageDescription。若維護舊代碼,委托方法 reverseGeocoder:didFindPlacemark: → CLGeocoder 的 completionHandler 邏輯一致,逐步替換即可。
精準的地址解析,是位置服務體驗的基石。