地图定位

  1 #import "ViewController.h"
  2 
  3 // 第一步:引入库头文件
  4 #import <CoreLocation/CoreLocation.h>
  5 
  6 
  7 @interface ViewController () <CLLocationManagerDelegate>
  8 
  9 /**  定位管理器  */
 10 @property (nonatomic, strong) CLLocationManager *manger;   //CoreLocation框架中CLLocationManager用于管理定位的管理器
 11 
 12 /**  编码与反编码的类  */
 13 @property (nonatomic, strong) CLGeocoder *geocoder;   //CoreLocation框架中CLGeocoder用于编码和反编码
 14 
 15 @end
 16 
 17 @implementation ViewController
 18 
 19 - (void)viewDidLoad {
 20     [super viewDidLoad];
 21     // Do any additional setup after loading the view, typically from a nib.
 22     
 23     
 24     // NSLocationWhenInUseUsageDescription来告诉用户使用定位服务的目的,并且注意这个配置是必须的,如果不进行配置则默认情况下应用无法使用定位服务,打开应用不会给出打开定位服务的提示,除非安装后自己设置此应用的定位服务。同时,在应用程序中需要根据配置对requestAlwaysAuthorization或locationServicesEnabled方法进行请求。由于本人机器已经更新到最新的iOS8.1下面的内容主要针对iOS8,使用iOS7的朋友需要稍作调整。
 25     
 26     // 定位的步骤:
 27     
 28     // 1.初始化定位管理器
 29     self.manger = [[CLLocationManager alloc] init];
 30     
 31     
 32     // 2.进行隐私的判断并授权
 33     // 进行隐私的判断
 34     if (![CLLocationManager locationServicesEnabled]) {
 35         NSLog(@"是否前往隐私进行设置允许定位");
 36         [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=privacy"]];
 37     }
 38     
 39     // 根据状态进行授权
 40     // 进行版本的判断
 41     if ([[[UIDevice currentDevice] systemVersion] integerValue] >= 8.0) {
 42         /*
 43          定位服务授权状态,返回枚举类型:
 44          kCLAuthorizationStatusNotDetermined: 用户尚未做出决定是否启用定位服务
 45          kCLAuthorizationStatusRestricted: 没有获得用户授权使用定位服务,可能用户没有自己禁止访问授权
 46          kCLAuthorizationStatusDenied :用户已经明确禁止应用使用定位服务或者当前系统定位服务处于关闭状态
 47          kCLAuthorizationStatusAuthorizedAlways: 应用获得授权可以一直使用定位服务,即使应用不在使用状态
 48          kCLAuthorizationStatusAuthorizedWhenInUse: 使用此应用过程中允许访问定位服务
 49          */
 50         /*
 51          在授权请求之前需要在inforPlist中设置允许定位的内容【需要在info.plist文件中添加的,设置提示语】
 52          NSLocationWhenInUseUsageDescription
 53          NSLocationAlwaysUsageDescription
 54          */
 55         if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse) {
 56             // 请求授权
 57             [self.manger requestWhenInUseAuthorization];
 58         }
 59     }
 60     
 61     
 62     // 3.设置管理器的代理和相关属性
 63     self.manger.delegate = self;
 64     
 65     // 设置经度
 66     self.manger.desiredAccuracy = 100;
 67     
 68     // 设置最小更新距离
 69     self.manger.distanceFilter = 100;
 70     
 71 
 72     // 4.开启定位
 73     [self.manger startUpdatingLocation];
 74     
 75     
 76     /************************************  编码与反编码  ****************************************/
 77     // 初始化对象
 78     self.geocoder = [[CLGeocoder alloc] init];
 79     
 80     // 根据地名获取经纬度
 81     [self getCoordinateByAdress:@"北京"];
 82     
 83     // 根据经纬度反编码取出地名
 84     [self getAddressByLatitude:34 Longitude:113];
 85     
 86     // 计算两点之间的距离
 87     [self distance];
 88 }
 89 
 90 
 91 #pragma mark - 计算两点之间的距离
 92 - (void)distance {
 93     
 94     // 创建两个位置
 95     CLLocation *locationBeijing = [[CLLocation alloc] initWithLatitude:40 longitude:116];
 96     CLLocation *locationDalian = [[CLLocation alloc] initWithLatitude:39 longitude:121];
 97     
 98     CLLocationDistance distance = [locationBeijing distanceFromLocation:locationDalian];
 99     NSLog(@"北京到大连的距离:%f", distance);
100 }
101 
102 
103 #pragma mark - 根据经纬度反编码取出地名
104 - (void)getAddressByLatitude:(CLLocationDegrees)latitude Longitude:(CLLocationDegrees)longitude {
105     
106     // 反编码
107     // 创建CLLocation
108     CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
109     [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
110         
111         NSDictionary *dic = placemarks.firstObject.addressDictionary;
112         NSLog(@"反编码地理位置信息:%@", dic);
113     }];
114 }
115 
116 
117 #pragma mark - 根据地名获取相关的信息
118 - (void)getCoordinateByAdress:(NSString *)address {
119     
120     // 编码方法
121     [_geocoder geocodeAddressString:address completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
122         
123         // 根据返回的地标,取出第一个位置(地标的位置很多)
124         CLPlacemark *mark = placemarks.firstObject;
125         
126         // 根据地标得到location
127         CLLocation *location = mark.location;
128         
129         // 根据mark获取区域
130         CLRegion *region = mark.region;
131         
132         // 获取字典信息
133         NSDictionary *addressDic = mark.addressDictionary;
134         
135         NSLog(@"地标位置:%@, 区域:%@, 地理位置信息:%@", location, region, addressDic);
136         
137 //        NSString *name=placemark.name;//地名
138 //        NSString *thoroughfare=placemark.thoroughfare;//街道
139 //        NSString *subThoroughfare=placemark.subThoroughfare; //街道相关信息,例如门牌等
140 //        NSString *locality=placemark.locality; // 城市
141 //        NSString *subLocality=placemark.subLocality; // 城市相关信息,例如标志性建筑
142 //        NSString *administrativeArea=placemark.administrativeArea; //143 //        NSString *subAdministrativeArea=placemark.subAdministrativeArea; //其他行政区域信息
144 //        NSString *postalCode=placemark.postalCode; //邮编
145 //        NSString *ISOcountryCode=placemark.ISOcountryCode; //国家编码
146 //        NSString *country=placemark.country; //国家
147 //        NSString *inlandWater=placemark.inlandWater; //水源、湖泊
148 //        NSString *ocean=placemark.ocean; // 海洋
149 //        NSArray *areasOfInterest=placemark.areasOfInterest; //关联的或利益相关的地标
150     }];
151 }
152 
153 
154 #pragma mark - CLLocationManagerDelegate的代理方法
155 // 定位成功之后开始更新位置信息,移动设置的最小距离之后也开始调用这个方法
156 - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
157     
158     // 获取最后一次的位置
159     CLLocation *location = locations.lastObject;
160     
161     // 获取位置
162     CLLocationCoordinate2D coordinate = location.coordinate;
163     
164     // 打印经度, 纬度, 海拔, 航海方向, 移动速度
165     NSLog(@"经度:%f, 纬度:%f, 海拔:%f, 航海方向:%f, 移动速度:%f", coordinate.longitude, coordinate.latitude, location.altitude, location.course, location.speed);
166     
167     // 为了节省电源,如果不使用定位,需要把定位关掉
168     [self.manger stopUpdatingLocation];
169 }
170 
171 
172 // 定位失败
173 - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
174     
175     NSLog(@"定位失败");
176 }
177 
178 @end

 如果定位失败,在模拟器的debug中设置一下,可能就好了

原文地址:https://www.cnblogs.com/zhizunbao/p/5546654.html