iOS 地圖與定位的簡單使用

ios地圖與定位的簡單使用

  1. 實現地圖、導航功能,每每須要先熟悉定位功能,在iOS中經過Core Location框架進行定位操做。Core Location自身能夠單獨使用,和地圖開發框架MapKit徹底是獨立的,可是每每地圖開發要配合定位框架使用。在Core Location中主要包含了定位、地理編碼(包括反編碼)功能。
  2. 代碼以下:ios

    #import "ViewController.h"
           #import <CoreLocation/CoreLocation.h>
    
           @interface ViewController ()<CLLocationManagerDelegate>
           /**聲明全局變量(記住緣由)  要懶加載**/
           @property(nonatomic,strong)CLLocationManager *LM;
           @end
    
           @implementation ViewController {
           CLLocation  *_location;
          }
          //懶加載
          -(CLLocationManager *)LM {
          if (!_LM) {
         _LM = [[CLLocationManager alloc]init];
         //代理
         _LM.delegate = self;
         [_LM requestAlwaysAuthorization];
         _LM.distanceFilter = 0.1;
         //定位最準確,耗電最快
         _LM.desiredAccuracy = kCLLocationAccuracyBest;
        }
        return _LM;
         }
       - (void)viewDidLoad {
     [super viewDidLoad];
    
        }
        //手勢點擊更新定位
       -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent     *)event{
         [self.LM startUpdatingLocation];
     }
       //代理事件
       -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
         CLLocation *locationsw= [locations firstObject];
          //    NSLog(@"%@",locationsw);
         /* 例如:」北偏東30度方向,移動了8米」
          實現步驟:
          1> 獲取對應的方向偏向(例如」正東」」東偏南」)
          2> 獲取對應的偏離角度(並判斷是不是正方向)
          3> 計算行走距離
          4> 打印信息
          */
         NSString *course = nil;
         switch ((int)locationsw.course /90) {
             case 0:
                 course = @"北偏東 ";
                 break;
             case 1:
                 course = @"東偏南";
                 break;
             case 2:
                 course = @"南偏西";
                 break;
             case 3:
                 course = @"西偏北";
             default:
                 break;
         }
         //度數
         NSString *degree = nil;
         degree = [NSString stringWithFormat:@"%d度",(int)locationsw.course%90];
         //距離
         NSString *distant = nil;
         if (_location) {
            distant = [NSString stringWithFormat:@"%f",[locationsw distanceFromLocation:_location]];
    
         }
        _location  =locationsw;
         NSLog(@"xiaoming %@%@移動%@",course,degree,distant);
    
     }
  3. 注意: 在Info.plist文件中添加以下配置:
    • NSLocationAlwaysUsageDescription
    • NSLocationWhenInUseUsageDescription
相關文章
相關標籤/搜索