概念:
地理编码: 根据给定的位置(通常是地名), 确定地理坐标(经纬度)
反地理编码: 根据给定的经纬度(地理坐标), 确定位置信息(街道, 门牌等)
#import "FirstViewController.h"
//引入定位 头文件
#import <CoreLocation/CoreLocation.h>
@interface FirstViewController ()
//编码属性
@property (strong, nonatomic) CLGeocoder *geocoder;
@end
@implementation FirstViewController
- (void)viewDidLoad {
[super viewDidLoad];
//1. 初始化编码对象
self.geocoder = [[CLGeocoder alloc] init];
//2. 调用自定义方法, 根据地名, 获取地标(地理编码)
[self getCoodinateByAddress:@"北京市"];
//3. 调用自定义方法, 实现反地理编码
[self getAddreddByLatitude:39.9200225351 longitude:39.9200225351];
}
#pragma mark ------ 第一部分: 地理编码 ------
- (void)getCoodinateByAddress:(NSString *)address{
//利用上面初始化的编码对象, 调用编码方法, 获取对应的地标
[self.geocoder geocodeAddressString:address completionHandler:^(NSArray<CLPlacemark *> * placemarks, NSError * error) {
//1. 获取第一个地标, 地标中存储了详细的地址信息. 注意: 一个地名可以搜索出多个地址
CLPlacemark *placeMark = [placemarks firstObject];
//2. 获取响应的属性信息
//获取位置
CLLocation *location = placeMark.location;
//获取区域
CLRegion *region = placeMark.region;
//地名
NSString *name = placeMark.name;
//街道
NSString *through = placeMark.thoroughfare;
//街道相关信息
NSString *subThruogh = placeMark.subThoroughfare;
//城市
NSString *locality = placeMark.locality;
//州
NSString *administrativeArea = placeMark.administrativeArea;
//其他行政区域信息
NSString *subAdministrativeArea = placeMark.subAdministrativeArea;
//邮编
NSString *postalCode = placeMark.postalCode;
//国家编码
NSString *ISOcountryCode = placeMark.ISOcountryCode;
//国家
NSString *country = placeMark.country;
//湖泊
NSString *inlandWater = placeMark.inlandWater;
//海洋
NSString *ocean = placeMark.ocean;
//关联或者相关联的地标
NSArray *areasOfInterest = placeMark.areasOfInterest;
# 打印地址字典中的信息
NSDictionary *dic = placeMark.addressDictionary;
NSLog(@"dic = %@", dic);
}];
}
#pragma mark -------- 反地理编码 --------
- (void)getAddreddByLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude{
//1. 初始化位置信息, 指定具体经纬度
CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
//2. 根据上面声明的编码对象, 调用反地理编码方法
[self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * placemarks, NSError * error) {
//3. 获取地标数组中的第一个
CLPlacemark *placeMark = [placemarks firstObject];
//4. 打印地标数组
NSLog(@"addressDictionary = %@", placeMark.addressDictionary);
}];
}
@end```