您的位置:首页 > 移动开发 > IOS开发

在iOS开发中自动获取当前的位置(GPS定位)

2014-04-11 11:28 537 查看
在iOS开发中自动获取当前的位置(GPS定位)

开发环境 xcode5.0

首先我们要引入这个框架CoreLocation.framework

将这个库引进来#import <CoreLocation/CoreLocation.h>

还有他的代理方法 CLLocationManagerDelegate

GPSViewController.h

注意这里的CLLocationManager* locationmanager要设置成全局变量,要不然得不到你想要的结果哦!具体为什么,我现在还不清楚

[objc] view
plaincopy





#import <UIKit/UIKit.h>

#import <CoreLocation/CoreLocation.h>

@interface GPSViewController : UIViewController<CLLocationManagerDelegate>

@property(nonatomic,retain) CLLocationManager* locationmanager;

@end

GPSViewController.m

[objc] view
plaincopy





#import "GPSViewController.h"

@interface GPSViewController ()

@end

@implementation GPSViewController

@synthesize locationmanager;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

if (self) {

// Custom initialization

}

return self;

}

- (void)viewDidLoad

{

[super viewDidLoad];

// Do any additional setup after loading the view.

locationmanager = [[CLLocationManager alloc]init];

//设置精度

/*

kCLLocationAccuracyBest

kCLLocationAccuracyNearestTenMeters

kCLLocationAccuracyHundredMeters

kCLLocationAccuracyHundredMeters

kCLLocationAccuracyKilometer

kCLLocationAccuracyThreeKilometers

*/

//设置定位的精度

[locationmanager setDesiredAccuracy:kCLLocationAccuracyBest];

//实现协议

locationmanager.delegate = self;

NSLog(@"开始定位");

//开始定位

[locationmanager startUpdatingLocation];

}

<pre code_snippet_id="278028" snippet_file_name="blog_20140406_2_4276648" name="code" class="objc"><pre code_snippet_id="278028" snippet_file_name="blog_20140406_2_4276648" name="code" class="objc">#pragma mark locationManager delegate

- (void)locationManager:(CLLocationManager *)manager

didUpdateToLocation:(CLLocation *)newLocation

fromLocation:(CLLocation *)oldLocation

{

NSLog(@"hello");

//打印出精度和纬度

CLLocationCoordinate2D coordinate = newLocation.coordinate;

NSLog(@"输出当前的精度和纬度");

NSLog(@"精度:%f 纬度:%f",coordinate.latitude,coordinate.longitude);

//停止定位

[locationmanager stopUpdatingLocation];

//计算两个位置的距离

float distance = [newLocation distanceFromLocation:oldLocation];

NSLog(@" 距离 %f",distance);

}

@end

</pre><br>

<br>

<pre></pre>

<pre code_snippet_id="278028" snippet_file_name="blog_20140406_2_4276648" name="code" class="objc"><pre code_snippet_id="278028" snippet_file_name="blog_20140406_2_4276648"></pre><pre code_snippet_id="278028" snippet_file_name="blog_20140406_2_4276648" name="code" class="objc"><pre code_snippet_id="278028" snippet_file_name="blog_20140406_2_4276648"></pre>

<pre></pre>

<pre></pre>

<pre></pre>

<pre></pre>

<pre></pre>

</pre></pre></pre>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: