在iOS开发中自动获取当前的位置(GPS定位)
在iOS开发中自动获取当前的位置(GPS定位)
开发环境 xcode5.0
首先我们要引入这个框架CoreLocation.framework
将这个库引进来#import <CoreLocation/CoreLocation.h>
还有他的代理方法 CLLocationManagerDelegate
GPSViewController.h
注意这里的CLLocationManager* locationmanager要设置成全局变量,要不然得不到你想要的结果哦!具体为什么,我现在还不清楚
- #import <UIKit/UIKit.h>
- #import <CoreLocation/CoreLocation.h>
- @interface GPSViewController : UIViewController<CLLocationManagerDelegate>
- @property(nonatomic,retain) CLLocationManager* locationmanager;
- @end
GPSViewController.m
- #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>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。