基于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;
}

效果图如下:


Paste_Image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 使用CLGeocoder可以完成“地理编码”和“反地理编码” 地理编码:根据给定的地名,获得具体的位置信息(比如经...
    IIronMan阅读 1,218评论 3 9
  • 简介 在移动互联网时代,移动app能解决用户的很多生活琐事,比如 周边:找餐馆、找KTV、找电影院等等 导航:根据...
    JonesCxy阅读 1,483评论 1 1
  • 出自http://my.oschina.net/are1OfBlog/blog/420034 摘要 现在很多社交、...
    JJO阅读 4,300评论 4 19
  • http://www.cnblogs.com/kenshincui/p/4125570.html 摘要: 现在很多...
    大崔老师阅读 3,434评论 1 2
  • 雨夜酒微凉,冷暖心自伤; 前日拾步伊摇琴,一歩一叹; 今来听雨叙叨肠,唏嘘已然; 花期花前花已落,花半相陪; 人是...
    渝名阅读 243评论 3 1

友情链接更多精彩内容