定位- 汽车导航
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()<CLLocationManagerDelegate>
/** 1. 定位管理者对象 ***/
@property (nonatomic, strong) CLLocationManager *mgr;
/** 上一次的位置 ***/
@property (nonatomic, strong) CLLocation *previousLocation;
/** 总路程 ***/
@property (nonatomic, assign) CLLocationDistance sumDistance;
/** 总时间 ***/
@property (nonatomic, assign) NSTimeInterval sumTime;
@end
@implementation ViewController
- (CLLocationManager *)mgr{
if (!_mgr) {
_mgr = [[CLLocationManager alloc] init];
}
return _mgr;
}
- (void)viewDidLoad {
[super viewDidLoad];
// 2. 设置代理
self.mgr.delegate = self;
// plist
// NSLocationAlwaysUsageDescription
// NSLocationWhenInUseUsageDescription
// 3. 开始监听
// 判断授权
if(IOS8){
[self.mgr requestAlwaysAuthorization];
}else{
[self.mgr startUpdatingLocation];
}
}
#pragma mark - 当授权状态改变时, 调用此方法
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
if (status == kCLAuthorizationStatusNotDetermined) {
LogYellow(@"正在授权中");
}else if ((status == kCLAuthorizationStatusAuthorizedAlways) || (status == kCLAuthorizationStatusAuthorizedWhenInUse)){
LogYellow(@"授权成功");
// 开始监听
[self.mgr startUpdatingLocation];
}else{
LogYellow(@"授权失败");
}
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
// 导航
/**
获取走了多远
获取走这段路花了多少时间
获取速度
获取总共多少路程
获取平均速度
*/
// 获取当前位置
CLLocation *newLocation = [locations lastObject];
if(self.previousLocation != nil){
// 计算两次距离
CLLocationDistance distance = [newLocation distanceFromLocation:self.previousLocation];
// 计算两次时间
NSTimeInterval dTime = [newLocation.timestamp timeIntervalSinceDate:self.previousLocation.timestamp];
// 计算速度
CGFloat speed = distance / dTime;
LogRed(@" %f, %f, %f",distance, dTime, speed);
// 累计时间
self.sumTime += dTime;
// 累计路程
self.sumDistance += distance;
// 计算平均速度
CGFloat avgSpeed = self.sumDistance / self.sumTime;
LogGreen(@"总路程 %f,总时间 %f,平均速度 %f",self.sumDistance, self.sumTime, avgSpeed);
}
// 记录上一次的位置
self.previousLocation = newLocation;
// 当前获取到 信息的时间
// location.timestamp
// 停止监听
// [self.mgr stopUpdatingLocation];
}
@end