Core Location是iPhone、iPad等开发定位服务应用程序的框架。我们要在Xcode中添加“CoreLocation.framework”存在的框架。
定位时候主要使用CLLocationManager、 CLLocationManagerDelegate和CLLocation。
CLLocationManager是定位服务管理类,它能够给我们提供获得设备的位置信息和高度信息,也可以监控设备进入或离开某个区域,它还可以帮助获得设备的运行方向等。
CLLocationManagerDelegate 是CLLocationManager类委托协议。
CLLocation类是封装了位置和高度信息。
实现:
<1>声明对象
@interface ViewController ()
{
CLLocationManager *_locationManager;
}
//经度
@property (weak, nonatomic) IBOutlet UITextField *txtLng;
//纬度
@property (weak, nonatomic) IBOutlet UITextField *txtLat;
//高度
@property (weak, nonatomic) IBOutlet UITextField *txtAlt;
<2>对象初始化
_locationManager=[[CLLocationManager alloc]init];
<3>询问用户是否启用定位服务
if (![CLLocationManager locationServicesEnabled])
{
NSLog(@”定位服务当前可能尚未打开,请设置打开!”);
return;
}
<4>设置代理
@interface ViewController ()
_locationManager.delegate = self;
<5>设置定位的其他
//设置定位精度 kCLLocationAccuracyBest为最精确定位
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
//设置定位频率,每隔多少米定位一次
_locationManager.distanceFilter = 10.0f;
<6>启动跟踪定位
[_locationManager startUpdatingLocation];
<7>
pragma mark - CoreLocation 代理
pragma mark 跟踪定位代理方法,每次位置发生变化即会执行(只要定位到相应位置)
-
(void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations
{
CLLocation *currLocation=[locations lastObject];//取出当前位置
self.txtLat.text = [NSString stringWithFormat:@”%3.5f”,
currLocation.coordinate.latitude];
self.txtLng.text = [NSString stringWithFormat:@”%3.5f”,
currLocation.coordinate.longitude];
self.txtAlt.text = [NSString stringWithFormat:@”%3.5f”,
currLocation.altitude];
//如果不需要实时定位,使用完即使关闭定位服务
[_locationManager stopUpdatingLocation];
}
%3.5f是输出整数部分是3位,小数部分是5位的浮点数。
在locationManager:didUpdateLocations:方法中参数locations是位置变化的集合,它按照时间变化的顺序存放。如果想获得当前设备的位置,可以使用第①行的[locations lastObject]语句获得集合中最后一个 元素,它就是设备当前位置了。
从集合中返回的对象类型是CLLocation,CLLocation封装了位置、高度等信息。在上面代码中我们使用了它的 两个属性:altitude和coordinate,altitude属性是高度值,coordinate是封装了经度和纬度的结构体 CLLocationCoordinate2D