獲取經緯度 CLLocation


 

//導入庫

#import <CoreLocation/CoreLocation.h>

 

//注意:

//需要在 info.plist 中導入前兩個字段

//NSLocationAlwaysUsageDescription

//NSLocationWhenInUseUsageDescription

 

@interface ViewController ()<CLLocationManagerDelegate>

 

@property (nonatomic,strong)CLLocationManager *locationManager;

 

@end

 

@implementation ViewController

 

 

- (void)viewDidLoad {

    [super viewDidLoad];

    

    //初始化locationManger管理器對象

    CLLocationManager *locationManager=[[CLLocationManager alloc]init];

    self.locationManager=locationManager;

    

    //判斷當前設備定位服務是否打開

    if (![CLLocationManager locationServicesEnabled]) {

        NSLog(@"設備尚未打開定位服務");

    }

 

    //判斷當前設備版本大於iOS8以后的話執行里面的方法

    if ([UIDevice currentDevice].systemVersion.floatValue >=8.0) {

        //持續授權

        [locationManager requestAlwaysAuthorization];

        //當用戶使用的時候授權

        [locationManager requestWhenInUseAuthorization];

    }

    

    //或者使用這種方式,判斷是否存在這個方法,如果存在就執行,沒有的話就忽略

    //if([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]){

    //   [locationManager requestWhenInUseAuthorization];

    //}

    

    //設置代理

    locationManager.delegate=self;

    //設置定位的精度

    locationManager.desiredAccuracy=kCLLocationAccuracyBest;

    //設置定位的頻率,這里我們設置精度為10,也就是10米定位一次

    CLLocationDistance distance=10;

    //給精度賦值

    locationManager.distanceFilter=distance;

    //開始啟動定位

    [locationManager startUpdatingLocation];

 

}

//當位置發生改變的時候調用(上面我們設置的是10,也就是當位置發生>10米的時候該代理方法就會調用)

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{

    //取出第一個位置

    CLLocation *location=[locations firstObject];

    NSLog(@"%@",location.timestamp);

    //位置坐標

    CLLocationCoordinate2D coordinate=location.coordinate;

    NSLog(@"您的當前位置:經度:%f,緯度:%f,海拔:%f,航向:%f,速度:%f",coordinate.longitude,coordinate.latitude,location.altitude,location.course,location.speed);

    //如果不需要實時定位,使用完即使關閉定位服務

    //[_locationManager stopUpdatingLocation];

}

 

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

@end


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM