iOS中CoreLocatio框架中的CLGeocoder 类不但为我们提供了地理编码方法,而且还提供了反地理编码:
同样需要导入框架:#import <CoreLocation/CoreLocation.h>
反地理编码方法:- (void)reverseGeocodeLocation:(CLLocation *)location completionHandler:(CLGeocodeCompletionHandler)completionHandler;
同样当反地理编码完成时,会调用 completionHandler
对象,该对象类型为 CLGeocodeCompletionHandler
,实际上是一个 block 对象
这个对象中传递了2个参数,其中placemark:
里面装了CLPlacemark
对象
Demo如下 :
@interface ViewController ()
//地理编码对象
@property (nonatomic ,strong) CLGeocoder *geocoder;
#pragma mark - 反地理编码
- (IBAction)reverseGeocode;
@property (weak, nonatomic) IBOutlet UITextField *longtitudeField;
@property (weak, nonatomic) IBOutlet UITextField *latitudeField;
@property (weak, nonatomic) IBOutlet UILabel *reverseDetailAddressLabel;
@end
@implementation ViewController
#pragma mark - 反地理编码响应
- (void)reverseGeocode
{
// 1.获取用户输入的经纬度
NSString *longtitude = self.longtitudeField.text;
NSString *latitude = self.latitudeField.text;
if (longtitude.length == 0 ||
longtitude == nil ||
latitude.length == 0 ||
latitude == nil) {
NSLog(@"请输入经纬度");
return;
}
// 2.根据用户输入的经纬度创建CLLocation对象
CLLocation *location = [[CLLocation alloc] initWithLatitude:[latitude doubleValue] longitude:[longtitude doubleValue]];
// 116.403857,39.915285
// 3.根据CLLocation对象获取对应的地标信息
[self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
for (CLPlacemark *placemark in placemarks) {
NSLog(@"%@ %@ %f %f", placemark.name, placemark.addressDictionary, placemark.location.coordinate.latitude, placemark.location.coordinate.longitude);
self.reverseDetailAddressLabel.text = placemark.locality;
}
}];
}
#pragma mark - 懒加载,创建地理编码对象
- (CLGeocoder *)geocoder
{
if (!_geocoder) {
_geocoder = [[CLGeocoder alloc] init];
}
return _geocoder;
}
效果图如下: