#import <CoreLocation/CoreLocation.h>
@interface OnePositionViewController ()<CLLocationManagerDelegate>
{
CLLocationManager *_manager;
CLGeocoder *_geocoder;
}
@property (nonatomic,strong)CLGeocoder *geocoder;
@property (weak, nonatomic) IBOutlet UILabel *latLabel;
@property (weak, nonatomic) IBOutlet UILabel *lngLabel;
@property (weak, nonatomic) IBOutlet UILabel *altLabel;
@property (weak, nonatomic) IBOutlet UILabel *locationLabel;
@end
@implementation OnePositionViewController
-(CLGeocoder *)geocoder{
if (!_geocoder) {
_geocoder = [[CLGeocoder alloc] init];
}
return _geocoder;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"地理定位和地理信息反编码";
if (![CLLocationManager locationServicesEnabled]) {
NSLog(@"用户关闭了定位");
return;
}
_manager = [[CLLocationManager alloc] init];
_manager.delegate = self;
_manager.desiredAccuracy = kCLLocationAccuracyBest;
_manager.distanceFilter = 1000.0f;
if ([_manager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
[_manager requestAlwaysAuthorization];
}
[_manager startUpdatingLocation];
}
#pragma mark -------- 授权状态发生变化时调用
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
switch (status) {
case kCLAuthorizationStatusNotDetermined:
if ([manager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
[manager requestWhenInUseAuthorization];
}
break;
default:
break;
}
}
#pragma mark - ------------ 定位成功
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray<CLLocation *> *)locations{
CLLocation *location = locations.lastObject;
NSLog(@"经度:%f",location.coordinate.latitude);
NSLog(@"纬度:%f",location.coordinate.longitude);
NSLog(@"高度:%f",location.altitude);
self.latLabel.text = [NSString stringWithFormat:@"经度:%f",location.coordinate.latitude];
self.lngLabel.text = [NSString stringWithFormat:@"纬度:%f",location.coordinate.longitude];
self.altLabel.text = [NSString stringWithFormat:@"高度:%f",location.altitude];
[self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
if (!error) {
CLPlacemark *placemark = placemarks[0];
NSLog(@"address = %@",placemark.addressDictionary);
NSDictionary *addressDictionary = placemark.addressDictionary;
NSString *address = addressDictionary[@"Country"];
NSString *addressState = addressDictionary[@"State"];
NSString *addressCity = addressDictionary[@"City"];
NSString *addressSubLocality = addressDictionary[@"SubLocality"];
NSString *addressThoroughfare = addressDictionary[@"Thoroughfare"];
self.locationLabel.text = [NSString stringWithFormat:@"%@ %@ %@ %@ %@",address,addressState,addressCity,addressSubLocality,addressThoroughfare];
[_manager stopUpdatingLocation];
}else{
NSLog(@"error:%@",error);
}
}];
}
#pragma mark ------- 定位失败
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error{
NSLog(@"error :%@",error);
}