如何在 iOS 中使用反向谷歌地理编码?
Posted
技术标签:
【中文标题】如何在 iOS 中使用反向谷歌地理编码?【英文标题】:How to use reverse Google GeoCoding in iOS? 【发布时间】:2015-01-27 08:15:09 【问题描述】:我是 ios 开发的新手。我使用 Google Map sdk 从 MapView 获取位置。我得到了当前位置,如纬度和经度,但现在我想从纬度和经度获取带有邮政编码的当前地址,如何可能,请给我解决方案。
【问题讨论】:
【参考方案1】:您可以使用 CLGeocoder:
__block CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:theLocation completionHandler:^(NSArray *placemarks, NSError *error)
if (error)
DDLogVerbose(@"Geocode failed with error: %@", error);
if([self.delegate respondsToSelector:@selector(geocodeFailed:)])
[self.delegate geocodeFailed:error];
return;
MKPlacemark *placemark = [placemarks lastObject];
if(placemark)
NSArray *shortDescArray = [placemark.addressDictionary valueForKey:@"FormattedAddressLines"];
NSString *shortDesc = [shortDescArray componentsJoinedByString:@", "];
DDLogVerbose(@"myPlacemark %@", placemark.addressDictionary);
else
DDLogVerbose(@"Geocode failed");
];
【讨论】:
【参考方案2】:您可以使用CLGeocoder
和reverseGeocodeLocation:completionHandler:
方法:
- (void)getAddressFromLocation:(CLLocation *)location completionHandler:(void (^)(NSMutableDictionary *placemark))completionHandler failureHandler:(void (^)(NSError *error))failureHandler
NSMutableDictionary *d = [NSMutableDictionary new];
CLGeocoder *geocoder = [CLGeocoder new];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error)
if (failureHandler && (error || placemarks.count == 0))
failureHandler(error);
else
CLPlacemark *placemark = [placemarks objectAtIndex:0];
if(completionHandler)
completionHandler(placemark.addressDictionary);
];
然后这样称呼它:
// Your location from latitude and longitude
CLLocation *location = [[CLLocation alloc] initWithLatitude:aLatitude longitude:aLongitude];
// Call the method to find the address
[self getAddressFromLocation:location completionHandler:^(NSMutableDictionary *d)
NSLog(@"address informations : %@", d);
NSLog(@"formatted address : %@", [placemark.addressDictionary valueForKey:@"FormattedAddressLines"]);
NSLog(@"Street : %@", [d valueForKey:@"Street"]);
NSLog(@"ZIP code : %@", [d valueForKey:@"ZIP"]);
NSLog(@"City : %@", [d valueForKey:@"City"]);
// etc.
failureHandler:^(NSError *error)
NSLog(@"Error : %@", error);
];
【讨论】:
我只想从这个地址的字典中获取一些数据,例如 CityName、Address、Street adesss、Zipcode 等如何获取? MKPlacemark 对象有一个addressDictionary
,您可以通过valueForKey
访问它: NSArray *shortDescArray = [placemark.addressDictionary valueForKey:@"FormattedAddressLines"];以上是关于如何在 iOS 中使用反向谷歌地理编码?的主要内容,如果未能解决你的问题,请参考以下文章