iOS开发iOS CollectioniOS开发专区

CoreLocation基本知识及使用

2015-11-17  本文已影响1156人  Andyzhao

知识简介

经纬度基本知识
经纬度基本知识.png
如何设置模拟器的经纬度
设置模拟器经纬度.png 杭州经纬度.png
用户隐私的保护
请求对话框.png
+ (BOOL)locationServicesEnabled;

从iOS 8开始,用户定位分两种情况
plist中添加字段.png

CoreLocation框架的使用

#import <CoreLocation/CoreLocation.h>

CLLocationManager的常用属性及操作
@property(assign, nonatomic) CLLocationDistance distanceFilter;
@property(assign, nonatomic) CLLocationAccuracy desiredAccuracy;
- (void)startUpdatingLocation;
- (void) stopUpdatingLocation;
// locations参数里面装着CLLocation对象
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations;
CLLocation用来表示某个位置的地理信息,比如经纬度、海拔等等
@property(readonly, nonatomic) CLLocationCoordinate2D coordinate;
@property(readonly, nonatomic) CLLocationDistance altitude;
@property(readonly, nonatomic) CLLocationDirection course;
@property(readonly, nonatomic) CLLocationSpeed speed;
- (CLLocationDistance)distanceFromLocation:(const CLLocation *)location

CoreLocation基本使用

实现步骤

1.获取用户的授权状态-->请求授权(info.plist-->NSLocationAlwaysUsageDescription/string)

2.请求用户的位置

3.获取用户的位置(CLLocation)

4.设置定位精确度desiredAccuracy/设置当用户移动多少距离,重新定位distanceFilter

5.计算两个经纬度之间距离(包装CLLocation对象-->distanceFromLocation)

#######代码如下


#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface ViewController () <CLLocationManagerDelegate>

/** 用户位置管理者对象 */
@property (nonatomic, strong) CLLocationManager *mgr;

@end

@implementation ViewController
#pragma mark - 懒加载
- (CLLocationManager *)mgr
{
    if (_mgr == nil) {
        self.mgr = [[CLLocationManager alloc] init];
        
        // 设置代理,在代理方法中可以拿到用户的位置
        self.mgr.delegate = self;
        
        // 设置定位的精度(精度越高越耗电)
        self.mgr.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
        
        // 设置当用户移动的时候,重新来定位
        self.mgr.distanceFilter = 10.0;
    }
    
    return _mgr;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 1.获取用户的授权状态(iOS7只要使用到定位,就会直接请求授权)
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (status == kCLAuthorizationStatusNotDetermined) {
        /*
        if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) {
            [mgr requestAlwaysAuthorization];
        }
         */
        if ([self.mgr respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            [self.mgr requestAlwaysAuthorization];
        }
    }
    
    // 2.开始定位(当调用该方法,系统就会不停的更新用户的位置)
    [self.mgr startUpdatingLocation];
    
    // 3.计算两个经纬度之间的距离
    [self countDistance];
}

- (void)countDistance
{
    // 北京:39.6 116.39
    // 杭州:30.3 120.2
    CLLocation *location1 = [[CLLocation alloc] initWithLatitude:39.6 longitude:116.39];
    CLLocation *location2 = [[CLLocation alloc] initWithLatitude:30.3 longitude:120.2];
    
    // 计算距离
    CLLocationDistance distance = [location1 distanceFromLocation:location2];
    NSLog(@"%.2f", distance);
}

#pragma mark - 实现CLLocationManager的代理方法
/**
 *  当获取到用户的位置就会执行该方法(如果仅仅是想拿到用户的位置,可以在获取到用户位置之后停止停止定位)
 *
 *  @param locations 数组中就存放着用户的位置(每更新到用户的一个位置,就会将用户位置的对象加入数组中)
 */
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    /*
     @property(readonly, nonatomic) CLLocationDistance altitude; // 海拔
     @property(readonly, nonatomic) CLLocationAccuracy horizontalAccuracy; // 水平精度
     @property(readonly, nonatomic) CLLocationAccuracy verticalAccuracy; // 垂直精度@property(readonly, nonatomic) CLLocationSpeed speed 手机当前的速度
         @property(readonly, nonatomic, copy) NSDate *timestamp; 时间戳
         @property(readonly, nonatomic, copy) CLFloor *floor 楼层
     */
    // 1.拿到用户位置的对象
    CLLocation *location = [locations lastObject];
    
    // 2.拿到用户当前位置的经纬度
    CLLocationCoordinate2D coordinate = location.coordinate;
    NSLog(@"latitude = %.2f", coordinate.latitude);
    NSLog(@"longitude = %.2f", coordinate.longitude);
    
    // [manager stopUpdatingLocation];
}

@end

注意点:使用模拟器获取当前位置时可能出现的不打印的情况,可能是以下原因

地理编码与反地理编码

CLGeocoder
地理编码方法
- (void)geocodeAddressString:(NSString *)addressString completionHandler:(CLGeocodeCompletionHandler)completionHandler;
反地理编码方法
- (void)reverseGeocodeLocation:(CLLocation *)location completionHandler:(CLGeocodeCompletionHandler)completionHandler;

CLGeocodeCompletionHandler
typedef void (^CLGeocodeCompletionHandler)(NSArray *placemarks, NSError *error);
CLPlacemark
@property (nonatomic, readonly) CLLocation *location;
@property (nonatomic, readonly) CLRegion *region;
@property (nonatomic, readonly) NSDictionary *addressDictionary;
@property (nonatomic, readonly) NSString *name;
@property (nonatomic, readonly) NSString *locality;

示例

布局.png
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>


@interface ViewController ()

// 地理编码
@property (weak, nonatomic) IBOutlet UITextField *textField;

// 反地理编码
@property (weak, nonatomic) IBOutlet UITextField *longitudeText;
@property (weak, nonatomic) IBOutlet UITextField *latitudeText;


/**编码使用的对象*/
@property (strong, nonatomic) CLGeocoder *geoCoder;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

// 反地理编码
- (IBAction)geoCoder:(id)sender {
    
    if (self.textField.text.length == 0) {
        
        NSLog(@"请输入详细信息");
        return;
    }
    
    // 地理编码
    [self.geoCoder geocodeAddressString:self.textField.text completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        if (error || placemarks.count == 0) {
            
            return ;
        }
        
        for (CLPlacemark *pm in  placemarks) {
            
            CLLocationCoordinate2D coordinate = pm.location.coordinate;
            
            // 获取经纬度
            NSLog(@"%.2f", coordinate.latitude);
            NSLog(@"%.2f", coordinate.longitude);
            
            // 获取所在的省
            NSLog(@"%@", pm.administrativeArea);
            // 获取详细信息(省、市)
            NSLog(@"%@", pm.name);
            
        }
        
    }];
}

// 反地理编码
- (IBAction)reverseGeocoder:(id)sender {
    
    
    NSString *latitude = self.latitudeText.text;
    NSString *longitude = self.longitudeText.text;
    
    if (latitude.length == 0 || longitude.length == 0 ){
        
        NSLog(@"请输入经纬度");
        
        return;
      }
    
    CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude.doubleValue longitude:longitude.doubleValue];
    
    [self.geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        for (CLPlacemark *pm in placemarks) {
            // 获取地址的全称
            NSLog(@"%@", pm.name);
            // 获取经纬度
            CLLocationCoordinate2D coordinate = pm.location.coordinate;
            NSLog(@"纬度:%.2f", coordinate.latitude);
            NSLog(@"经度:%.2f", coordinate.longitude);
            
            // 获取城市
            NSLog(@"所在城市:%@", pm.administrativeArea);
            NSLog(@"所在城市:%@", pm.locality);
        }

        
    }];
    
    
}

#pragma mark - 懒加载
- (CLGeocoder *)geoCoder
{

    if (_geoCoder == nil) {
        
        _geoCoder = [[CLGeocoder alloc] init];
    }
    
    return _geoCoder;
}
@end


上一篇 下一篇

猜你喜欢

热点阅读