一、简介

在移动互联网时代,移动app能解决用户的很多生活琐事,比如
导航:去任意陌生的地方
周边:找餐馆、找酒店、找银行、找电影院
 
在上述应用中,都用到了地图和定位功能,在iOS开发中,要想加入这2大功能,必须基于2个框架进行开发
Map Kit :用于地图展示
Core Location :用于地理定位
 
2个热门专业术语
LBS :Location Based Service
p、SoLoMo :Social Local Mobile(索罗门)
 
 
CoreLocation框架使用须知
CoreLocation框架中所有数据类型的前缀都是CL
CoreLocation中使用CLLocationManager对象来做用户定位
 
 
二、CLLocationManager
CLLocationManager的常用操作
开始用户定位
- (void)startUpdatingLocation;
 
停止用户定位
- (void) stopUpdatingLocation;
 
当调用了startUpdatingLocation方法后,就开始不断地定位用户的位置,中途会频繁地调用代理的下面方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations;
locations参数里面装着CLLocation对象
 
@property(assign, nonatomic) CLLocationDistance distanceFilter;
每隔多少米定位一次
 
@property(assign, nonatomic) CLLocationAccuracy desiredAccuracy;
定位精确度(越精确就越耗电)
 
三、CLLocation
CLLocation用来表示某个位置的地理信息,比如经纬度、海拔等等
@property(readonly, nonatomic) CLLocationCoordinate2D coordinate;
经纬度
 
@property(readonly, nonatomic) CLLocationDistance altitude;
海拔
 
@property(readonly, nonatomic) CLLocationDirection course;
路线,航向(取值范围是0.0° ~ 359.9°,0.0°代表真北方向)
 
@property(readonly, nonatomic) CLLocationSpeed speed;
行走速度(单位是m/s)
 
用- (CLLocationDistance)distanceFromLocation:(const CLLocation *)location方法可以计算2个位置之间的距离
 
 
三、CLLocationCoordinate2D
CLLocationCoordinate2D是一个用来表示经纬度的结构体,定义如下

typedef struct {

CLLocationDegrees latitude; // 纬度

CLLocationDegrees longitude; // 经度

} CLLocationCoordinate2D;

一般用CLLocationCoordinate2DMake函数来创建CLLocationCoordinate2D
 
四、CLGeocoder
使用CLGeocoder可以完成“地理编码”和“反地理编码”
地理编码:根据给定的地名,获得具体的位置信息(比如经纬度、地址的全称等)
反地理编码:根据给定的经纬度,获得具体的位置信息
 
地理编码方法
- (void)geocodeAddressString:(NSString *)addressString completionHandler:(CLGeocodeCompletionHandler)completionHandler;
 
反地理编码方法
- (void)reverseGeocodeLocation:(CLLocation *)location completionHandler:(CLGeocodeCompletionHandler)completionHandler;
 
CLGeocodeCompletionHandler
当地理\反地理编码完成时,就会调用CLGeocodeCompletionHandler
typedef void (^CLGeocodeCompletionHandler)(NSArray *placemarks, NSError *error);
这个block传递2个参数
error :当编码出错时(比如编码不出具体的信息)有值
placemarks :里面装着CLPlacemark对象
 
五、CLPlacemark
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;
城市
 
 
代码:定位、指南针、区域检测
 //
// ViewController.m
// IOS_0403_导航
//
// Created by ma c on 16/4/3.
// Copyright © 2016年 博文科技. All rights reserved.
// #import "ViewController.h"
#import <CoreLocation/CoreLocation.h> @interface ViewController ()<CLLocationManagerDelegate> @property (nonatomic, strong) CLLocationManager *mgr; //上一次位置
@property (nonatomic, strong) CLLocation *previousLocation;
//总路程
@property (nonatomic, assign) CLLocationDistance sumDistance;
//总时间
@property (nonatomic, assign) NSTimeInterval sumTime; @property (nonatomic, strong) UIImageView *commpasspointer; @end @implementation ViewController /*
注意:iOS7只要定位,系统就会自动要求用户对你的应用程序授权,但是从iOS8开始想要定位
必须自己主动要求用户授权,然后在Info.plist文件中配置一项属性才能弹出授权窗口
NSLocationWhenInUseDescription,允许在前台获取GPS的描述
NSLocationAlwaysUsageDescription,允许在后台获取GPS的描述 CLLocation
location.coordinate; 坐标, 包含经纬度
location.altitude; 设备海拔高度 单位是米
location.course; 设置前进方向 0表示北 90东 180南 270西
location.horizontalAccuracy; 水平精准度
location.verticalAccuracy; 垂直精准度
location.timestamp; 定位信息返回的时间
location.speed; 设备移动速度 单位是米/秒, 适用于行车速度而不太适用于不行 CLHeading
magneticHeading 设备与磁北的相对角度
trueHeading 设置与真北的相对角度, 必须和定位一起使用, iOS需要设置的位置来计算真北
真北始终指向地理北极点
磁北对应随着时间变化的地球磁场北极 CLRegion 代表一个区域
>CLCircularRegion 圆形区域
>CLBeaconRegion 蓝牙信号区域
*/ - (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor cyanColor]; [self test]; //添加指南针图片
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg_compasspointer"]];
imgView.center = self.view.center;
[self.view addSubview:imgView];
self.commpasspointer = imgView;
} - (void)test
{
//1.创建管理者
// CLLocationManager *mgr = [[CLLocationManager alloc] init];
//2.设置代理
self.mgr.delegate = self; //设置获取位置精确度
self.mgr.desiredAccuracy = kCLLocationAccuracyBest;
//设置多久获取一次
self.mgr.distanceFilter = ; if ([[UIDevice currentDevice].systemVersion doubleValue] > 8.0) {
//主动请求授权
[self.mgr requestAlwaysAuthorization];
} //3.开始定位
[self.mgr startUpdatingLocation]; //3.开始获取用户方向
[self.mgr startUpdatingHeading]; //3.开始区域检测
//创建中心点
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(, );
//创建圆形区域
CLCircularRegion *circularRegion = [[CLCircularRegion alloc] initWithCenter:center radius: identifier:@"北京"];
[self.mgr startMonitoringForRegion:circularRegion]; } #pragma mark - CLLocationManagerDelegate
//当获取到位置时调用
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
//获取当前位置
CLLocation *newLocation = [locations lastObject]; NSLog(@"%f,%f",newLocation.coordinate.latitude,newLocation.coordinate.longitude); if (self.previousLocation == nil) { //计算两次之间的位置(单位为米)
CLLocationDistance distance = [newLocation distanceFromLocation:self.previousLocation];
//计算两次之间的时间(单位为秒)
NSTimeInterval dTime = [newLocation.timestamp timeIntervalSinceDate:self.previousLocation.timestamp];
//计算速度
CGFloat speed = distance / dTime; //累加时间
self.sumTime += dTime;
//累加路程
self.sumDistance += distance;
//计算平均速度
CGFloat averSpeed = self.sumDistance / self.sumTime;
}
//记录上一次位置
self.previousLocation = newLocation; } //当获取到用户方向时调用
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
//1.将角度转换成弧度
CGFloat angle = newHeading.magneticHeading * M_PI / ;
//2.旋转图片
self.commpasspointer.transform = CGAffineTransformIdentity;
self.commpasspointer.transform = CGAffineTransformMakeRotation(-angle);
} //进入监听区域时调用
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
{
NSLog(@"didEnterRegion");
} //离开监听区域时调用
- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region
{
NSLog(@"didExitRegion");
} #pragma mark - 懒加载
- (CLLocationManager *)mgr
{
if(!_mgr){
_mgr = [[CLLocationManager alloc] init]; }
return _mgr;
} @end

地理编码

 //
// ViewController.m
// IOS_0403_地理编码
//
// Created by ma c on 16/4/3.
// Copyright © 2016年 博文科技. All rights reserved.
// #import "ViewController.h"
#import <CoreLocation/CoreLocation.h> @interface ViewController ()
//-------------------正向地理编码----------------//
/**
* 监听地理编码点击事件
*/
- (IBAction)geocodeBtnClick;
/**
* 需要编码的地址容器
*/
@property (weak, nonatomic) IBOutlet UITextField *addressField;
/**
* 经度容器
*/
@property (weak, nonatomic) IBOutlet UILabel *longitudeLabel;
/**
* 纬度容器
*/
@property (weak, nonatomic) IBOutlet UILabel *latitudeLabel;
/**
* 详情容器
*/
@property (weak, nonatomic) IBOutlet UILabel *detailAddressLabel;
/**
* 地理编码对象
*/ //-------------------反向地理编码----------------//
- (IBAction)reverseGeocode;
@property (weak, nonatomic) IBOutlet UITextField *longtitudeField;
@property (weak, nonatomic) IBOutlet UITextField *latitudeField;
@property (weak, nonatomic) IBOutlet UILabel *reverseDetailAddressLabel; @property (nonatomic ,strong) CLGeocoder *geocoder; @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
}
//正向地理编码
- (IBAction)geocodeBtnClick
{
// 0.获取用户输入的位置
NSString *addressStr = self.addressField.text;
if (addressStr == nil || addressStr.length == ) {
NSLog(@"请输入地址");
return;
} // 1.创建地理编码对象 // 2.利用地理编码对象编码
// 根据传入的地址获取该地址对应的经纬度信息
[self.geocoder geocodeAddressString:addressStr completionHandler:^(NSArray *placemarks, NSError *error) { if (placemarks.count == || error != nil) {
return ;
}
// placemarks地标数组, 地标数组中存放着地标, 每一个地标包含了该位置的经纬度以及城市/区域/国家代码/邮编等等...
// 获取数组中的第一个地标
CLPlacemark *placemark = [placemarks firstObject];
// for (CLPlacemark *placemark in placemarks) {
// NSLog(@"%@ %@ %f %f", placemark.name, placemark.addressDictionary, placemark.location.coordinate.latitude, placemark.location.coordinate.longitude);
self.latitudeLabel.text = [NSString stringWithFormat:@"%f", placemark.location.coordinate.latitude];
self.longitudeLabel.text = [NSString stringWithFormat:@"%f", placemark.location.coordinate.longitude];
NSArray *address = placemark.addressDictionary[@"FormattedAddressLines"];
NSMutableString *strM = [NSMutableString string];
for (NSString *str in address) {
[strM appendString:str];
}
self.detailAddressLabel.text = strM;
// } }];
}
//反向地理编码
- (IBAction)reverseGeocode
{
// 1.获取用户输入的经纬度
NSString *longtitude = self.longtitudeField.text;
NSString *latitude = self.latitudeField.text;
if (longtitude.length == ||
longtitude == nil ||
latitude.length == ||
latitude == nil) {
NSLog(@"请输入经纬度");
return;
} // 2.根据用户输入的经纬度创建CLLocation对象
CLLocation *location = [[CLLocation alloc] initWithLatitude:[latitude doubleValue] longitude:[longtitude doubleValue]]; // 3.根据CLLocation对象获取对应的地标信息
[self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) { for (CLPlacemark *placemark in placemarks) {
NSLog(@"%@ %@ %f %f", placemark.name, placemark.addressDictionary, placemark.location.coordinate.latitude, placemark.location.coordinate.longitude);
self.reverseDetailAddressLabel.text = placemark.locality;
}
}];
} #pragma mark - 懒加载
- (CLGeocoder *)geocoder
{
if(!_geocoder){
_geocoder = [[CLGeocoder alloc] init]; }
return _geocoder;
} @end
 

IOS-CoreLocation的更多相关文章

  1. IOS CoreLocation框架的使用(用于地理定位)

    ●  在移动互联网时代,移动app能解决用户的很多生活琐事,比如 ●  导航:去任意陌生的地方 ●  周边:找餐馆.找酒店.找银行.找电影院 ●  在上述应用中,都用到了地图和定位功能,在iOS开发中 ...

  2. iOS - CoreLocation 定位

    前言 NS_CLASS_AVAILABLE(10_6, 2_0) @interface CLLocationManager : NSObject 1.CoreLocation 定位 配置 1.在 iO ...

  3. IOS深入学习

    iOS超全开源框架.项目和学习资料汇总(1)UI篇 iOS超全开源框架.项目和学习资料汇总(2)动画篇 iOS超全开源框架.项目和学习资料汇总(3)网络和Model篇 数据库 FMDB – sqlit ...

  4. iOS开发——高级篇——地理定位 CoreLocation

    一.CoreLocation 在移动互联网时代,移动app能解决用户的很多生活琐事,比如周边:找餐馆.找KTV.找电影院等等导航:根据用户设定的起点和终点,进行路线规划,并指引用户如何到达 在上述应用 ...

  5. iOS开发拓展篇—CoreLocation简单介绍

    iOS开发拓展篇—CoreLocation简单介绍 一.简介 1.在移动互联网时代,移动app能解决用户的很多生活琐事,比如 (1)导航:去任意陌生的地方 (2)周边:找餐馆.找酒店.找银行.找电影院 ...

  6. iOS开发拓展篇—CoreLocation定位服务

    iOS开发拓展篇—CoreLocation定位服务 一.简单说明 1.CLLocationManager CLLocationManager的常用操作和属性 开始用户定位- (void)startUp ...

  7. iOS开发拓展篇—CoreLocation地理编码

    iOS开发拓展篇—CoreLocation地理编码 一.简单说明 CLGeocoder:地理编码器,其中Geo是地理的英文单词Geography的简写. 1.使用CLGeocoder可以完成“地理编码 ...

  8. iOS:地图:MapKit和CoreLocation

    地图:MapKit和CoreLocation 简介: 现在很多的社交软件都引入了地图和定位功能,要想实现这2大功能,那就不得不学习其中的2个框架:MaKit和CoreLocation CoreLoca ...

  9. 【iOS】7.4 定位服务->2.1.1 定位 - 官方框架CoreLocation: 请求用户授权

    本文并非最终版本,如果想要关注更新或更正的内容请关注文集,联系方式详见文末,如有疏忽和遗漏,欢迎指正. 本文相关目录: ================== 所属文集:[iOS]07 设备工具 === ...

  10. 【iOS】7.4 定位服务->2.1.2 定位 - 官方框架CoreLocation: CLLocationManager(位置管理器)

    本文并非最终版本,如果想要关注更新或更正的内容请关注文集,联系方式详见文末,如有疏忽和遗漏,欢迎指正. 本文相关目录: ================== 所属文集:[iOS]07 设备工具 === ...

随机推荐

  1. chrome命令

    chrome://settings(设置) chrome://extensions(扩展程序) chrome://history(历史记录) chrome://settings/clearBrowse ...

  2. 【MonogDB】The description of index(二) Embedded and document Index

    In this blog, we will talk about another the index which was called "The embedded ". First ...

  3. asp.net Mvc Npoi 导出导入 excel

    因近期项目遇到所以记录一下: 首先导出Excel : 首先引用NPOI包 http://pan.baidu.com/s/1i3Fosux (Action一定要用FileResult) /// < ...

  4. django重写用户模型

    重写一个UserProfile继承自带的AbstractUser # -*- coding: utf-8 -*- from __future__ import unicode_literals fro ...

  5. Python(函数式编程)

    函数是Python内建支持的一种封装,我们通过把大段代码拆成函数,通过一层一层的函数调用,就可以把复杂任务分解成简单的任务,这种分解可以称之为面向过程的程序设计.函数就是面向过程的程序设计的基本单元. ...

  6. js 改变文章字体大小

    //设置页面文字大小 function SetFontSize(areaid, size) { document.getElementById(areaid).style.fontSize = siz ...

  7. Linux服务器内存cache清理

    发现cache中占用大量内存,无free内存可用 使用如下命令清理: syncsysctl -w vm.drop_caches=1 转自:http://blog.csdn.net/sky_qing/a ...

  8. Linux网络接口配置文件ifcfg-eth0解析

    本文转自:http://blog.csdn.net/jmyue/article/details/17288467 在Windows上配置网络比较容易,有图形化界面可操作.在Linux中往往是通过命令修 ...

  9. Sybase:获取本月最后一天的日期的实现方法

    Sybase:获取本月最后一天的日期的实现方法 Oracle中查询月底那天的日期的函数为:last_day(). 在ASE中没有对应的函数,在Oracle移植到Sybase的时候,需要手动编写函数来实 ...

  10. 做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)?

    import random import string def GenKey(length): chars = string.ascii_letters + string.digits return ...