iOS定位 - CoreLocation

2016-01-21  本文已影响1064人  再见远洋
一、CLLocationManager介绍

在开始说CoreLocation之前我必须先来介绍一下CLLocationManager 因为定位服务使用的管理类就是它 下面先来说说CLLocationManager的常用操作和属性:

* 每隔多少米定位一次

@property(assign, nonatomic) CLLocationDistance distanceFilter;

定位精确度(越精确就越耗电)

@property(assign, nonatomic) CLLocationAccuracy desiredAccuracy;

 

##### 二、CLLocation的简单介绍

说完CLLocationManager  那么我们继续来介绍CLLocation,它使用来表示某个位置的地理信息,比如经纬度、海拔等等

* 经纬度 

@property(readonly, nonatomic) CLLocationCoordinate2D coordinate;

* 海拔 

@property(readonly, nonatomic) CLLocationDistance altitude;

* 路线,航向(取值范围是0.0° ~ 359.9°,0.0°代表真北方向)

@property(readonly, nonatomic) CLLocationDirection course;

* 行走速度(单位是m/s)

@property(readonly, nonatomic) CLLocationSpeed speed;

* 计算2个位置之间的距离

- (CLLocationDistance)distanceFromLocation:(const CLLocation *)location方法

 

##### 三、CLLocationCoordinate2D的简单介绍

看上去这个类好像很高大上的样子 2D都出来了感觉是不是跟3D也有关系呢  其实没那么神秘 CLLocationCoordinate2D其实就是一个用来表示经纬度的结构体,定义如下

typedef struct {

    CLLocationDegrees latitude; // 纬度

    CLLocationDegrees longitude; // 经度

} CLLocationCoordinate2D;

一般用CLLocationCoordinate2DMake函数来创建 这个我想大家抖动的 OC中的结构体 几乎都是使用XXXMake的方式来创建 但是有一个NSRange有点特殊 它是使用NSMakeRange的方式创建的  好了  好像有点扯远了 那下面我就使用代码来给大家演示一下

//
// ViewController.m
// 一次定位
//
// Created by 远洋 on 16/1/15.
// Copyright © 2016年 yuanyang.com. All rights reserved.
//

import "ViewController.h"

import <CoreLocation/CoreLocation.h>

@interface ViewController ()<CLLocationManagerDelegate>

//全局的位置管理对象manager
@property(nonatomic,strong)CLLocationManager *locationManager;

@end

@implementation ViewController

pragma mark - /********比较两个位置之间的直线距离*******/

-(void)compareDistance{
//获取第一个点的位置
CLLocation * location1 = [[CLLocation alloc]initWithLatitude:40 longitude:119];

//第二个点的位置
CLLocation * location2 = [[CLLocation alloc]initWithLatitude:39 longitude:120];

//计算两个点之间的直线距离 单位是米
CLLocationDistance distance = [location1 distanceFromLocation:location2];

NSLog(@"%lf",distance / 1000);

}

pragma mark - /********定位的代理方法*******/

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
NSLog(@"%@",locations);
[self.locationManager stopUpdatingLocation];
}
@end

注意点 :必须要特别注意的一点是 很多人 都会忘记用户授权 这一步 或者是忘记 在info.plist文件中添加key值
*   判断设备是否需要请求授权 8.0之后必须请求授权

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

    //    [locationManager requestAlwaysAuthorization];
    
    //设置一次授权
    [locationManager requestWhenInUseAuthorization];
}
* 配置info.plist文件

 ![屏幕快照 2016-01-21 下午1.31.16.png](https://img.haomeiwen.com/i1361619/64844fa923d3fa28.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
上一篇 下一篇

猜你喜欢

热点阅读