导入第三方类库
#import <CoreLocation/CoreLocation.h>
声明属性
@interface ViewController ()<CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) CLGeocoder *geoCoder;
@end
在ViewDidLoad中写属性和方法
- (void)viewDidLoad {
[super viewDidLoad];
// 初始化
self.locationManager = [[CLLocationManager alloc] init];
// 设置代理
self.locationManager.delegate = self;
// 定位精度
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
// 设置多少米更新一次距离
self.locationManager.distanceFilter = 100;
// 什么时候请求位置信息
[self.locationManager requestAlwaysAuthorization];
// 开始请求位置信息
[self.locationManager startUpdatingLocation];
// 将位置信息转换为经纬度
[self.geoCoder geocodeAddressString:@"信阳" completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *pm = [placemarks firstObject];
// 经度
CGFloat longitude = pm.location.coordinate.longitude;
// 纬度
CGFloat latitude = pm.location.coordinate.latitude;
NSLog(@"经度:%f, 纬度:%f", longitude, latitude);
}];
}
代理方法
// 定位成功
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
// 将地理位置转换为汉字
CLLocation *location = [locations firstObject];
[self.geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
if (error) {
NSLog(@"%@", [error localizedDescription]);
} else {
CLPlacemark *pm = [placemarks firstObject];
NSLog(@"%@", pm.addressDictionary);
}
}];
// NSLog(@"%@", location);
// NSLog(@"纬度:%f", location.coordinate.latitude);
// NSLog(@"经度%f", location.coordinate.longitude);
}
// 定位失败
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
// 错误信息描述
NSLog(@"%@", [error localizedDescription]);
}
#pragma mark - 懒加载方法
- (CLGeocoder *)geoCoder
{
if (!_geoCoder) {
_geoCoder = [[CLGeocoder alloc] init];
}
return _geoCoder;
}