定位CoreLocation

一、定位
iOS三种定位方式: CoreLocation
按定位的准确性: GPS(Global Positioning System全球定位系统); 蜂窝式基站; wifi;

定位顺序:
1. 首选GPS:
    1) 前提: 室内肯定不会用GPS
2. wifi —> 最经济实惠的
3. 基站

GPS:
优点: 定位最准确;
缺点: 最费电; 最费流量;

功能/内容:
1. 单纯的定位 CoreLocation Framework
    1) 常用的类:
     CLLocationManager;  
     CLLocationManagerDelegate;
     CLLocation;

 2.定位的步骤:
    1) #import <CoreLocation/CoreLocation.h>
    2) 遵循协议CLLocationManagerDelegate
     3) 创建CLLocationManager对象
    4) 设置代理, 并实现协议的方法

3. 针对ios8+以上版本的定位设置:
1) 申请用户的权限(前台和后台):
a、[self.mgr requestAlwaysAuthorization];
b、——> NSLocationAlwaysUsageDescription加到plist文件中
2) 只申请前台的用户权限:
a、[self.mgr requestWhenInUseAuthorization];
b、—-> NSLocationWhenInUseUsageDescription加到plist文件中
 
二、地理编码
地理编码: 给定一个地名, 获得这个地名的位置信息(经纬度, 地址) CLGeocoder
常用类: CLGeocoder;  CLPlacemark;
[self.geoCoder geocodeAddressString:name completionHandler:^(NSArray *placemarks, NSError *error) {}];

反地理编码: 给定一个经纬度, 获取经纬度的位置
常用类: CLGeocoder;  CLPlacemark;
[self.geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {}];


结合地图来定位
//--------------------------------------------------------------------------------------------
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface ViewController () <CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *mgr;

@end

@implementation ViewController
//懒加载初始化管理者对象
- (CLLocationManager *)mgr {
    if (!_mgr) {
        _mgr = [CLLocationManager new];
    }
    return _mgr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //设置代理
    self.mgr.delegate = self;
    if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) {
        //plist设置
        [self.mgr requestWhenInUseAuthorization];
    } else {
        //ios7
        NSLog(@"ios7");
        [self.mgr startUpdatingLocation];
    }
}
//用户是否授权代理方法
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        NSLog(@"用户授权成功");
        //开始定位
        [self.mgr startUpdatingLocation];
    } else if (status == kCLAuthorizationStatusDenied) {
        NSLog(@"用户授权拒绝");
    }
}
//定位成功后的代理
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    NSLog(@"%s", __func__);//用来查询当前执行的方法
    //locations数组按照顺序存放; 最新的定位位置放在数组的最后面
    CLLocation *location = [locations lastObject];
    NSLog(@"定位后的位置: %f, %f, %f", location.coordinate.latitude, location.coordinate.longitude, location.speed);
    //停止定位
    [self.mgr stopUpdatingLocation];
}
//--------------------------------------------------------------------------------------------
posted @ 2016-05-04 14:33  bonjour520  阅读(175)  评论(0编辑  收藏  举报