现在的位置: 首页 > 综合 > 正文

在 iOS 应用中使用 GPS

2013年12月11日 ⁄ 综合 ⁄ 共 2073字 ⁄ 字号 评论关闭
在 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程序。

抱歉!评论已关闭.