@interface LocationViewController () <CLLocationManagerDelegate>
// CLLocationManager(位置管理器)
@property(nonatomic, strong) CLLocationManager *locationManager;
@end
@implementation LocationViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc] init];
// delegate:响应CLLocationManagerdelegate的对象
self.locationManager.delegate = self;
/*
desiredAccuracy:位置的精度属性:
kCLLocationAccuracyBest; 精确度最佳
kCLLocationAccuracyNearestTenMeters; 精确度10m以内
kCLLocationAccuracyHundredMeters; 精确度100m以内
kCLLocationAccuracyKilometer; 精确度1000m以内
kCLLocationAccuracyThreeKilometers; 精确度3000m以内
*/
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
// distanceFilter:横向移动多少距离后更新位置信息 位置发生100米偏移时 重新定位
self.locationManager.distanceFilter = 100;
if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
[self.locationManager requestAlwaysAuthorization];
// 需要在plist文件中添加默认缺省的字段“NSLocationAlwaysUsageDescription”,这个提示是:“允许应用程序在您并未使用该应用程序时访问您的位置吗?”NSLocationAlwaysUsageDescription对应的值是告诉用户使用定位的目的或者是标记。
// 需要在plist文件中添加默认缺省的字段“NSLocationWhenInUseDescription”,这个时候的提示是:“允许应用程序在您使用该应用程序时访问您的位置吗?”
[self.locationManager requestWhenInUseAuthorization];
}
// 开始定位
[self.locationManager startUpdatingLocation];
}
//
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
switch (status) {
case kCLAuthorizationStatusNotDetermined:
if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
[self.locationManager requestWhenInUseAuthorization];
}
break;
default:
break;
}
}
//- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
//
// NSLog(@"经度 = %f 纬度 = %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
// self.LatitudeLabel.text = [NSString stringWithFormat:@"%f", newLocation.coordinate.latitude];
// self.LongitudeLabel.text = [NSString stringWithFormat:@"%f", newLocation.coordinate.longitude];
//
//}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *currLocation = [locations lastObject];
NSLog(@"经度=%f 纬度=%f", currLocation.coordinate.latitude, currLocation.coordinate.longitude);
// 关闭定位
[self.locationManager stopUpdatingLocation];
// 根据经纬度 反向编码 获取详细地址
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:currLocation
completionHandler:^(NSArray *placemarks, NSError *error){
for (CLPlacemark *place in placemarks) {
NSLog(@"thoroughfare,%@",place.thoroughfare); // 街道
NSLog(@"subThoroughfare,%@",place.subThoroughfare); // 子街道
NSLog(@"locality,%@",place.locality); // 市
NSLog(@"subLocality,%@",place.subLocality); // 区
NSLog(@"country,%@",place.country); // 国家
}
}];
}
@end