操作步骤
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];
}