No1 CoreLocation实现地理定位

来源:互联网 发布:明朝为什么会灭亡 知乎 编辑:程序博客网 时间:2024/05/22 16:37

一 简介

  • 在iOS开发中,实现定位和地图功能,必须基于2个框架进行开发

    • CoreLocation :用于地理定位,地理编码,区域监听等(着重功能实现)
    • MapKit :用于地图展示,例如大头针,路线、覆盖层展示等(着重界面展示)
  • 2个热门专业术语

    • LBS :Location Based Service
    • SoLoMo :Social Local Mobile(索罗门)
  • CoreLocation框架使用须知

    • CoreLocation框架中所有数据类型的前缀都是CL
    • CoreLocation中使用CLLocationManager对象来做用户定位

二 版本适配

  • iOS8.0之前的定位

    • 前台定位

      • 1.导入CoreLocation框架和对应的主头文件
      • 2.创建CLLcationManager对象,并设置代理

          _locationM = [[CLLocationManager alloc] init]; _locationM.delegate = self;
      • 3.调用CLLcationManager对象的startUpdatingLocation方法进行更新用户位置

        [_locationM startUpdatingLocation];
      • 4.实现代理方法,接收位置参数

        -(void)locationManager:(nonnull CLLocationManager *)manager didUpdateLocations:(nonnull NSArray<CLLocation *> *)locations
    • 后台定位
      这里写图片描述

用户隐私的保护:
开发者可以在Info.plist中设置NSLocationUsageDescription说明定位的目的(Privacy - Location Usage Description)
这里写图片描述

  • iOS8.0+ 至 iOS9.0之前的定位

    • 前台定位
      • 1.导入CoreLocation框架和对应的主头文件
      • 2.创建CLLcationManager对象,并设置代理 请求前台定位授权,并配置KEY
        _locationM = [[CLLocationManager alloc] init];_locationM.delegate = self;  if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0)     {     // 请求允许在前台获取用户位置的授权    [_locationM requestWhenInUseAuthorization];     } 

    这里写图片描述

    • 3.调用CLLcationManager对象的startUpdatingLocation方法进行更新用户位置(同上)
    • 4.实现代理方法,接收位置参数(同上)

      • 后台定位
      • 方案一 (同上)
      • 注意:如果APP处于后台,则会出现蓝条
      • 方案二:请求前后台定位授权,并配置KEY
        // 请求允许在前后台都能获取用户位置的授权[_locationM requestAlwaysAuthorization];

      这里写图片描述

  • 用户各种授权状态讲解

switch (status) {            // 用户还未决定        case kCLAuthorizationStatusNotDetermined:        {            NSLog(@"用户还未决定");            break;        }            // 问受限        case kCLAuthorizationStatusRestricted:        {            NSLog(@"访问受限");            break;        }            // 定位关闭时和对此APP授权为never时调用        case kCLAuthorizationStatusDenied:        {            // 定位是否可用(是否支持定位或者定位是否开启)            if([CLLocationManager locationServicesEnabled])            {                NSLog(@"定位开启,但被拒");            }else            {                NSLog(@"定位关闭,不可用");            }            break;        }            // 获取前后台定位授权        case kCLAuthorizationStatusAuthorizedAlways://        case kCLAuthorizationStatusAuthorized: // 失效,不建议使用        {            NSLog(@"获取前后台定位授权");            break;        }            // 获得前台定位授权        case kCLAuthorizationStatusAuthorizedWhenInUse:        {            NSLog(@"获得前台定位授权");            break;        }        default:            break;    }
  • iOS9.0 定位

    • 前台定位(同上)
    • 后台定位

      • 方案一:在APP处于前台定位授权场景下,勾选后台运行模式update locations (如下图) 并且,调用以下方法,设置允许后台定位

         if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) { // 如果在iOS9.0+想要在前台授权模式下,在后台获取用户位置,需要额外设置以下属性为YES    _locationM.allowsBackgroundLocationUpdates = YES;    }

        这里写图片描述

      • 方案二 :(同上)
  • 请求一次位置

    • 按照定位精确度从低到高进行排序,逐个进行定位
[_locationM requestLocation];
// 定位精确度越高, 越耗电, 而且, 定位时间越长   kCLLocationAccuracyBestForNavigation // 最适合导航   kCLLocationAccuracyBest; // 最好的   kCLLocationAccuracyNearestTenMeters; // 附近10米   kCLLocationAccuracyHundredMeters; // 100米   kCLLocationAccuracyKilometer; // 1000米   kCLLocationAccuracyThreeKilometers; // 3000米

一次定位使用注意:
一:要实现代理的定位失败方法;

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error

二:不能与startUpdatingLocation同时使用。

  • CLLocation对象
 coordinate (当前位置所在的经纬度) altitude   (海拔) speed  (当前速度) -distanceFromLocation: (获取两个位置之间的直线物理距离)
 // 判断当前位置是否可用  CLLocation *location = [locations lastObject]; // horizontalAccuracy : 如果是负数, 代表当前位置不可用    if(location.horizontalAccuracy < 0)          return;

三 指南针

  • 使用步骤

    • 1.导入CoreLocation框架和对应的主头文件
    • 2.创建CLLcationManager对象,并设置代理
    • 3.调用CLLcationManager对象的startUpdatingHeading方法进行更新设备朝向

      [_locationM startUpdatingHeading];   // 获取当前设备朝向
    • 4.实现代理方法,获取方向参数,根据方向参数旋转图片

      -(void)locationManager:(nonnull CLLocationManager *)manager didUpdateHeading:(nonnull CLHeading *)newHeading    {        // 获取当前设备朝向(磁北方向)        CGFloat angle = newHeading.magneticHeading;       // 转换成为弧度        CGFloat radian = angle / 180.0 * M_PI;        // 反向旋转指南针        [UIView animateWithDuration:0.5 animations:^{            self.compassView.transform = CGAffineTransformMakeRotation(-radian);        }];    }

    注意: 获取用户的设备朝向,不需要用户进行定位授权

四 区域监听

  • 步骤

    • 1.导入CoreLocation框架和对应的主头文件
    • 2.创建CLLcationManager对象,并设置代理,请求授权(iOS8.0之后才需要) 请求前后台定位授权,并配置KEY
    • 3.调用CLLcationManager对象的startMonitoringForRegion:方法进行监听指定区域

      // 创建区域中心CLLocationCoordinate2D center = CLLocationCoordinate2DMake(29.12345, 131.23456);// 创建区域(指定区域中心,和区域半径) CLCircularRegion *region = [[CLCircularRegion alloc] initWithCenter:center radius:1000 identifier:@"XXX"];// 开始监听指定区域[self.locationM startMonitoringForRegion:region];
    • 4.实现代理方法,获取区域进入或者离开状态

       // 进去监听区域后调用(调用一次)-(void)locationManager:(nonnull CLLocationManager *)manager didEnterRegion:(nonnull CLRegion *)region    {        NSLog(@"进入区域---%@", region.identifier);        [manager stopMonitoringForRegion:region];    }// 离开监听区域后调用(调用一次)-(void)locationManager:(nonnull CLLocationManager *)manager didExitRegion:(nonnull CLRegion *)region    {        NSLog(@"离开区域---%@", region.identifier);    }

五 (反)地理编码

  • 创建CLGeocoder对象
  _geoC = [[CLGeocoder alloc] init];
  • 地理编码方案1
    • 直接根据地址进行地理编码(返回结果可能有多个,因为一个地点有重名)
 [self.geoC geocodeAddressString:@"XX商务园" completionHandler:^(NSArray<CLPlacemark *> * __nullable placemarks, NSError * __nullable error) {    // 包含区,街道等信息的地标对象    CLPlacemark *placemark = [placemarks firstObject];    // 城市名称    // NSString *city = placemark.locality;    // 街道名称    // NSString *street = placemark.thoroughfare; // 全称 NSString *name = placemark.name; self.addressDetailTV.text = [NSString stringWithFormat:@"%@", name]; self.latitudeTF.text = [NSString stringWithFormat:@"%f", placemark.location.coordinate.latitude]; self.longtitudeTF.text = [NSString stringWithFormat:@"%f", placemark.location.coordinate.longitude];            }];
  • 地理编码方案2
    • 根据地址和指定区域两个条件进行地理编码(更加精确)
  [self.geoC geocodeAddressString:@"广州" inRegion:nil completionHandler:^(NSArray<CLPlacemark *> * __nullable placemarks, NSError * __nullable error) {  // 包含区,街道等信息的地标对象  CLPlacemark *placemark = [placemarks firstObject];  self.addressDetailTV.text = placemark.description;  self.latitudeTF.text = [NSString stringWithFormat:@"%f", placemark.location.coordinate.latitude];  self.longtitudeTF.text = [NSString stringWithFormat:@"%f", placemark.location.coordinate.longitude];            }];
  • 反地理编码
 // 创建CLLocation对象 CLLocation *location = [[CLLocation alloc] initWithLatitude:23.132931 longitude:113.375924; // 根据CLLocation对象进行反地理编码 [self.geoC reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * __nullable placemarks, NSError * __nullable error) { // 包含区,街道等信息的地标对象 CLPlacemark *placemark = [placemarks firstObject];                // 城市名称        //        NSString *city = placemark.locality;                // 街道名称        //        NSString *street = placemark.thoroughfare;  // 全称  NSString *name = placemark.name;  self.addressDetailTV.text = [NSString stringWithFormat:@"%@", name];            }];

六 定位的第三方框架

  • 下载框架(locationManager框架)
    locationManager框架 下载地址
  • 导入框架(直接拖入项目)
  • 框架功能说明
    • 可以使用block进行获取用户位置
    • 可以设置超时时长
    • 可以取消和强制终止定位
1 0