您的位置:首页 > 移动开发 > IOS开发

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

2017-07-07 19:11 429 查看
猫猫分享,必须精品

原创文章,欢迎转载。转载请注明:翟乃玉的博客

地址: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;


结构图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: