iOS自带定位功能(转载//www.greatytc.com/p/e28f055f4107)

由于公司的项目中只需要一个定位的功能,于是想到了苹果自带定位功能。废话不多说,直接上代码。

实现、

1、导入头文件,并且遵循CLLocationManagerDelegate协议#import

2、声明一个全局的定位管理者变量

@property (nonatomic,strong) CLLocationManager *manager;

3、实例化对象,设置代理,请求授权(不经过授权不能适应定位)

// 实例化对象

_manager = [[CLLocationManager alloc] init];

_manager.delegate = self;

// 请求授权,记得修改的infoplist,NSLocationAlwaysUsageDescription(描述)

[_manager requestAlwaysAuthorization];

4、实现其代理方法

#pragma mark - 代理方法,当授权改变时调用

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {

// 获取授权后,通过

if (status == kCLAuthorizationStatusAuthorizedAlways) {

//开始定位(具体位置要通过代理获得)

[_manager startUpdatingLocation];

//设置精确度

_manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;

//设置过滤距离

_manager.distanceFilter = 1000;

//开始定位方向

[_manager startUpdatingHeading];

}

}

#pragma mark - 方向

- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading {

//输出方向

//地理方向

NSLog(@"true = %f ",newHeading.trueHeading);

// 磁极方向

NSLog(@"mag = %f",newHeading.magneticHeading);

}

#pragma mark - 定位代理

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {

//    NSLog(@"%@",locations);

//获取当前位置

CLLocation *location = manager.location;

//获取坐标

CLLocationCoordinate2D corrdinate = location.coordinate;

//打印地址

NSLog(@"latitude = %f longtude = %f",corrdinate.latitude,corrdinate.longitude);

// 地址的编码通过经纬度得到具体的地址

CLGeocoder *gecoder = [[CLGeocoder alloc] init];

[gecoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {

CLPlacemark *placemark = [placemarks firstObject];

//打印地址

NSLog(@"%@",placemark.name);

}];

// 通过具体地址去获得经纬度

CLGeocoder *coder = [[CLGeocoder alloc] init];

[coder geocodeAddressString:@"天河城" completionHandler:^(NSArray *placemarks, NSError *error) {

NSLog(@"_________________________反编码");

CLPlacemark *placeMark = [placemarks firstObject];

NSLog(@"%@ lati = %f long = %f",placeMark.name,placeMark.location.coordinate.latitude,placeMark.location.coordinate.longitude);

}];

//停止定位

[_manager stopUpdatingLocation];

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容