猫猫学iOS 之CoreLocation反地理编码小Demo输入经纬度得到城市

来源:互联网 发布:滴胶手机壳 知乎 编辑:程序博客网 时间:2024/05/29 18:01

猫猫分享,必须精品

原创文章,欢迎转载。转载请注明:翟乃玉的博客
地址:http://blog.csdn.net/u013357243

一:效果

输入经纬度,可以得到相应的地名
这里写图片描述

二:思路

跟地里编码差不多
1.获取用户输入的经纬度
2.根据用户输入的经纬度创建CLLocation对象
3.根据CLLocation对象获取对应的地标信息

三:代码

#import "ViewController.h"#import <CoreLocation/CoreLocation.h>@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- (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]];    // 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;}@end

四:知识扩充CLGeocoder

使用CLGeocoder可以完成“地理编码”和“反地理编码”
地理编码:根据给定的地名,获得具体的位置信息(比如经纬度、地址的全称等)
反地理编码:根据给定的经纬度,获得具体的位置信息

->地理编码方法

- (void)geocodeAddressString:(NSString *)addressString completionHandler:(CLGeocodeCompletionHandler)completionHandler;

->反地理编码方法

- (void)reverseGeocodeLocation:(CLLocation *)location completionHandler:(CLGeocodeCompletionHandler)completionHandler;

CLGeocodeCompletionHandler

当地理\反地理编码完成时,就会调用

CLGeocodeCompletionHandler typedef void (^CLGeocodeCompletionHandler)(NSArray *placemarks, NSError *error);

这个block传递2个参数
error :当编码出错时(比如编码不出具体的信息)有值
placemarks :里面装着CLPlacemark对象

CLPlacemark

CLPlacemark的字面意思是地标,封装详细的地址位置信息

地理位置

@property (nonatomic, readonly) CLLocation *location;

区域

@property (nonatomic, readonly) CLRegion *region;

详细的地址信息

@property (nonatomic, readonly) NSDictionary *addressDictionary;

地址名称

@property (nonatomic, readonly) NSString *name;

城市

@property (nonatomic, readonly) NSString *locality;

结构图

这里写图片描述

12 1