Core Location是iOS SDK中一个提供设备位置的框架。可以使用三种技术来获取位置:GPS、蜂窝或WiFi。在这些技术中,GPS最为精准,如果有GPS硬件,Core Location将优先使用它。如果设备没有GPS硬件(如WiFi iPad)或使用GPS获取当前位置时失败,Core Location将退而求其次,选择使用蜂窝或WiFi。
Core Location的大多数功能是由位置管理器(CLLocationManager)提供的,可以使用位置管理器来指定位置更新的频率和精度,以及开始和停止接收这些更新。
要使用位置管理器,必须首先将框架Core Location加入到项目中,再导入其接口文件:
#import <CoreLocation/CoreLocation.h>
并初始化位置管理器,指定更新代理,以及一些更新设置,然后更新
CLLocationManager *locManager = [[CLLocationManager alloc] init];
locManager.delegate = self;
[locManager startUpdatingLocation];
位置管理器委托(CLLocationManagerDelegate)有两个与位置相关的方法:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *curLocation = [locations lastObject];
if(curLocation.horizontalAccuracy > 0)
{
NSLog(@"当前位置:%.0f,%.0f +/- %.0f meters",curLocation.coordinate.longitude,
curLocation.coordinate.latitude,
curLocation.horizontalAccuracy);
}
if(curLocation.verticalAccuracy > 0)
{
NSLog(@"当前海拔高度:%.0f +/- %.0f meters",curLocation.altitude,curLocation.verticalAccuracy);
}
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{ //此方法为定位失败的时候调用。并且由于会在失败以后重新定位,所以必须在末尾停止更新
if(error.code == kCLErrorLocationUnknown)
{
NSLog(@"Currently unable to retrieve location.");
}
else if(error.code == kCLErrorNetwork)
{
NSLog(@"Network used to retrieve location is unavailable.");
}
else if(error.code == kCLErrorDenied)
{
NSLog(@"Permission to retrieve location is denied.");
[manager stopUpdatingLocation];
}
}
第一个方法处理定位成功,manager参数表示位置管理器实例;locations为一个数组,是位置变化的集合,它按照时间变化的顺序存放。如果想获得设备的当前位置,只需要访问数组的最后一个元素即可。集合中每个对象类型是CLLocation,它包含以下属性:
coordinate — 坐标。一个封装了经度和纬度的结构体。
altitude — 海拔高度。正数表示在海平面之上,而负数表示在海平面之下。
horizontalAccuracy — 位置的精度(半径)。位置精度通过一个圆表示,实际位置可能位于这个圆内的任何地方。这个圆是由coordinate(坐标)和horizontalAccuracy(半径)共同决定的,horizontalAccuracy的值越大,那么定义的圆就越大,因此位置精度就越低。如果horizontalAccuracy的值为负,则表明coordinate的值无效。










