在某些應用情境中,我們除了取得經緯度座標之外,還希望能進一步得知使用者目前所在的城市與國家名稱。這可以透過 CLGeocoder 進行「反向地理編碼(Reverse Geocoding)」來達成:把已知的經緯度轉換為人類可讀的地址資訊。
以下示範如何在取得座標後,解析出城市與國家名稱:
- (void)getReverseGeocode {
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
if (currentLatLong.count > 0) {
CLLocationCoordinate2D myCoOrdinate;
myCoOrdinate.latitude = LatValue;
myCoOrdinate.longitude = LangValue;
CLLocation *location = [[CLLocation alloc] initWithLatitude:myCoOrdinate.latitude
longitude:myCoOrdinate.longitude];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
if (error) {
NSLog(@"failed with error: %@", error);
return;
}
if (placemarks.count > 0) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSString *MyAddress = @"";
if ([placemark.addressDictionary objectForKey:@"FormattedAddressLines"] != NULL) {
MyAddress = [[placemark.addressDictionary objectForKey:@"FormattedAddressLines"]
componentsJoinedByString:@", "];
} else {
MyAddress = @"Address Not founded";
}
NSString *city = @"";
if ([placemark.addressDictionary objectForKey:@"SubAdministrativeArea"] != NULL) {
city = [placemark.addressDictionary objectForKey:@"SubAdministrativeArea"];
} else if ([placemark.addressDictionary objectForKey:@"City"] != NULL) {
city = [placemark.addressDictionary objectForKey:@"City"];
} else if ([placemark.addressDictionary objectForKey:@"Country"] != NULL) {
city = [placemark.addressDictionary objectForKey:@"Country"];
} else {
city = @"City Not founded";
}
NSLog(@"%@", city);
NSLog(@"%@", MyAddress);
}
}];
}
}
這段程式碼的核心在於 reverseGeocodeLocation:completionHandler::完成後會回傳一個 CLPlacemark 陣列,我們再依序從 SubAdministrativeArea、City、Country 等欄位中嘗試取出城市與國家資訊。由於不同地區的地址結構可能有差異,因此採取逐層降級的判斷方式,能有效提升解析的成功率。