iOS--CoreLocation地理反地理编码

操作步骤

1.导入框架
CoreLocation/CoreLocation.h
2.设置属性
@property (nonatomic, strong) CLGeocoder *geocoder;
3.方法实现
3.1 懒加载创建geocoder属性

- (CLGeocoder *)geocoder
{
    if (!_geocoder) {
        self.geocoder = [[CLGeocoder alloc] init];
    }
    return _geocoder;
}

3.2 地理编码

//地理
- (void)dili
{
    //地理编码方法

    NSString *straddress = @"北京";

    [self.geocoder geocodeAddressString:straddress completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error) { // 有错误
            NSLog(@"找不到该地址");
        } else { // 编码成功

            // 取出最前面的地址
            CLPlacemark *pm = [placemarks firstObject];

            // 取出经纬度
            CGFloat  latitude = pm.location.coordinate.latitude;
            CGFloat longitude =  pm.location.coordinate.longitude;



            //NSLog(@"总共找到%d个地址", placemarks.count);

            for (CLPlacemark *pm in placemarks) {
                NSLog(@"-----地址开始----");

                NSLog(@"%f %f %@", pm.location.coordinate.latitude, pm.location.coordinate.longitude, pm.name);

                [pm.addressDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
                    NSLog(@"%@ %@", key, obj);
                }];

                NSLog(@"-----地址结束----");
            }
        }
    }];
}

3.3 反地理编码

//反地理
- (void)fandili
{
    //反地理编码

    // 1.位置
    CLLocationDegrees latitude = 114.0;
    CLLocationDegrees longitude = 45.0;
    CLLocation *loc = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];

    // 2.反地理编码
    [self.geocoder reverseGeocodeLocation:loc completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error) { // 有错误(地址乱输入)
            NSLog(@"找不到该地址");
        } else { // 编码成功
            // 取出最前面的地址
            CLPlacemark *pm = [placemarks firstObject];
            NSLog(@"%@", pm.name);
            // 设置具体地址

            NSLog(@"总共找到%ld个地址", (long)placemarks.count);

            for (CLPlacemark *pm in placemarks) {
                NSLog(@"-----地址开始----");

                NSLog(@"%f %f %@", pm.location.coordinate.latitude, pm.location.coordinate.longitude, pm.name);

                [pm.addressDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
                    NSLog(@"%@ %@", key, obj);
                }];

                NSLog(@"-----地址结束----");
            }
        }
    }];
}

3.4 调用方法

- (void)viewDidLoad {
    [super viewDidLoad];


    [self dili];
    [self fandili];
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值