在 iOS 应用中使用 GPS

在 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]);
}
...

    测量精度有以下几类,精度越高越消耗电力。

kCLLocationAccuracyNearestTenMeters10m
kCLLocationAccuracyHundredMeters100m
kCLLocationAccuracyKilometer1km
kCLLocationAccuracyThreeKilometers3km

    因为在模拟器上不能设置经纬度,所以只能在实际设备中测试你的GPS程序。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值