代碼以下: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); }