From http://fecbob.pixnet.net/blog/post/35423944

在 iOS 應用中使用 GPS大致分下麵兩步:1、添加 CoreLocation.framework;2、生成 CLLocationManager 測量位置。 測試代碼如下: // LocationViewCtrl.h #import UIKit/UIKit.h #import CoreLocation/CoreLocation.h @inter

在 iOS 應用中使用 GPS大致分下麵兩步:1、添加 CoreLocation.framework;2、生成 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
kCLLocationAccuracyThreeKilometers 3km

 

因為在模擬器上不能設置經緯度,所以只能在實際設備中測試你的GPS程式。
arrow
arrow
    全站熱搜

    zer931 發表在 痞客邦 留言(0) 人氣()