简单地介绍一下GPS的使用方法。使用GPS大致分下面两步。 添加CoreLocation.framework。 生成CLLocationManager 测量位置。 测试代码如下: // LocationViewCtrl.h #import <UIKit/UIKit.h> #import <CoreLocation/CoreLocation.h> @interface LocationViewCtrl : UIViewController <CLLocationManagerDelegate>{ CLLocationManager *man; } @property(nonatomic, retain) CLLocationManager *man; @end LocationViewCtrl.m #import "LocationViewCtrl.h" #import <CoreLocation/CoreLocation.h> @implementation LocationViewCtrl @synthesize man; - (void)viewDidLoad { [super viewDidLoad]; man = [[CLLocationManager alloc] init]; // 如果可以利用本地服务时 if([man locationServicesEnabled]){ // 接收事件的实例 man.delegate = self; // 发生事件的的最小距离间隔(缺省是不指定) man.distanceFilter = kCLDistanceFilterNone; // 精度(缺省是Best) man.desiredAccuracy = kCLLocationAccuracyBest; // 开始测量 [man startUpdatingLocation]; } } // 如果GPS测量成果以下的函数被调用 - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{ // 取得经纬度 CLLocationCoordinate2D coordinate = newLocation.coordinate; CLLocationDegrees latitude = coordinate.latitude; CLLocationDegrees longitude = coordinate.longitude; // 取得精度 CLLocationAccuracy horizontal = newLocation.horizontalAccuracy; CLLocationAccuracy vertical = newLocation.verticalAccuracy; // 取得高度 CLLocationDistance altitude = newLocation.altitude; // 取得时刻 NSDate *timestamp = [newLocation timestamp]; // 以下面的格式输出format: <latitude>, <longitude>> +/- <accuracy>m @ <date-time> NSLog([newLocation description]); // 与上次测量地点的间隔距离 if(oldLocation != nil){ CLLocationDistance d = [newLocation getDistanceFrom:oldLocation]; NSLog([NSString stringWithFormat:@"%f", d]); } } // 如果GPS测量失败了,下面的函数被调用 - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{ NSLog([error localizedDescription]); } ... 测量精度有以下几类,精度越高越消耗电力。 kCLLocationAccuracyNearestTenMeters 10m kCLLocationAccuracyHundredMeters 100m kCLLocationAccuracyKilometer 1km kCLLocationAccuracyThreeKilometers3km 因为在模拟器上不能设置经纬度,所以只能在实际设备中测试你的GPS程序。 |