基于CLGeocoder - 反地理编码

iOS中CoreLocatio框架中的CLGeocoder 类不但为我们提供了地理编码方法,而且还提供了反地理编码:

同样需要导入框架:

#import <CoreLocation/CoreLocation.h>
反地理编码方法:

- (void)reverseGeocodeLocation:(CLLocation *)location completionHandler:(CLGeocodeCompletionHandler)completionHandler;
同样当反地理编码 成时,会调用  completionHandler 对象,该对象类型为  CLGeocodeCompletionHandler,实际上是一个 block 对象

这个对象中传递了2个参数,其中placemark:里面装了CLPlacemark对象

步骤:

1、创建地理编码对象

2、获取用户的地理坐标(经纬度)

3、根据地理坐标创建CLLocation对象

4、根据CLLocation对象获取对象坐标信息


< 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;
}
效果图如下:


控制面板信息:



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值