几乎全部的苹果设备都有GPS模块,经过GPS模块能够得到设备的当前位置信息,能够经过CLLocationManager和其代理类CLLocationManagerDelegate来得到启动和中止跟踪,并得到设备当前经的纬度信息。另外,还能够为设备进入某个特定区域作出提示。经过下面的程序,当用户点击按钮,开始跟踪设备,并经过UILabel实时显示当前设备的经纬度信息。实现步骤以下所示。
建立项目并为项目添加CoreLocation.framework框架。
在界面上添加UIButton和UILabel组件。
在.h中实现CLLocationManagerDelegate代理,声明CLLocationManager属性和UILabel属性,并声明UIButton的点击事件方法。
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface AmakerViewController : UIViewController<CLLocationManagerDelegate>
- (IBAction)start:(id)sender;
@property (strong, nonatomic) IBOutlet UILabel *myLocatoinInfo;
@property (strong,nonatomic) CLLocationManager *lm;
@end
在viewDidLoad方法中判判定位服务是否能够利用,实例化并指定属性。
- (void)viewDidLoad
{
[super viewDidLoad];
if ([CLLocationManager locationServicesEnabled]) {
self.lm = [[CLLocationManager alloc]init];
self.lm.delegate = self;
// 最小距离
self.lm.distanceFilter=kCLDistanceFilterNone;
}else{
NSLog(@"定位服务不可利用");
}
}
在CLLocationManagerDelegate的更新方法中实时得到最新位置信息,并显示在UILabel中。
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation{
self.myLocatoinInfo.text = [NSString stringWithFormat:@"[%f,%f]",newLocation.coordinate.latitude,newLocation.coordinate.longitude];
}
在UIButton的点击事件中启动跟踪。
- (IBAction)start:(id)sender {
if (self.lm!=nil) {
[self.lm startUpdatingLocation];
}
}
程序的运行结果以下图所示。git