這一回簡單地介紹一下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程式
作者:易飛揚