iOS 5.0がリリースされてからかなり経ちますが、いつの間にかiOSでも正ジオコーディングがサポートされていたんですね。気付きませんでした。
逆ジオコーディングも同じCLGeocoderで簡単に行う事が出来ます。
CLGeocoder *geocoder;
geocoder = [CLGeocoder alloc];
geocoder = [geocoder init];
[geocoder geocodeAddressString:text completionHandler:^(NSArray *placemarks, NSError *error) {
if (error) {
NSLog(@"Geocode failed with error: %@", error); return;
}
CLPlacemark* placemark;
for(placemark in placemarks) {
NSLog(@"name : %@", placemark.name);
NSLog(@"ocean : %@", placemark.ocean);
NSLog(@"postalCode : %@", placemark.postalCode);
NSLog(@"subAdministrativeArea : %@", placemark.subAdministrativeArea);
NSLog(@"subLocality : %@", placemark.subLocality);
NSLog(@"subThoroughfare : %@", placemark.subThoroughfare);
NSLog(@"thoroughfare : %@", placemark.thoroughfare);
NSLog(@"administrativeArea : %@", placemark.administrativeArea);
NSLog(@"inlandWater : %@", placemark.inlandWater);
NSLog(@"ISOcountryCode : %@", placemark.ISOcountryCode);
NSLog(@"locality : %@", placemark.locality);
NSLog(@"addressDictionary CountryCode : %@", [placemark.addressDictionary objectForKey:@"CountryCode"]);
NSLog(@"addressDictionary Country : %@", [placemark.addressDictionary objectForKey:@"Country"]);
NSLog(@"addressDictionary ZIP : %@", [placemark.addressDictionary objectForKey:@"ZIP"]);
NSLog(@"addressDictionary State : %@", [placemark.addressDictionary objectForKey:@"State"]);
NSLog(@"addressDictionary SubLocality : %@", [placemark.addressDictionary objectForKey:@"SubLocality"]);
NSString* name;
name = ABCreateStringWithAddressDictionary(placemark.addressDictionary, YES);
NSLog(@"%@", name);
}
}];
使い方は簡単。上記のgeocodeAddressStringに地名や住所を渡して挙げるだけです。
結果はplacemarksにCLPlacemarkのアレイとして返って来ます。
アレイになって返ってくるのは、例えば地名として「新宿駅」を検索すると複数の住所が返ってくるからです。
CLPlacemarkのリファレンスにも あるように、このクラスは様々な住所に関するメンバーを持っています。
しかし正ジオコーディングにおいては殆ど使い物になりません。
値がセットされていたり、されていなかったり。
多分、これをまた逆ジオコーディングしてやると色々セットされてくるのじゃないかと思いますが、それは試していません。
使えるかな?と思ったのはaddressDictionaryです。
NSDictionary *addressDictionary
これをABCreateStringWithAddressDictionary()に渡してあげれば住所として読めるようなNSStringに変換してくれます。
NSString* name; name = ABCreateStringWithAddressDictionary(placemark.addressDictionary, YES); NSLog(@"%@", name);