引入框架
#import <CoreLocation/CoreLocation.h>
遵守代理
<CLLocationManagerDelegate>
需要字段
@property (strong, nonatomic) CLLocationManager *manager;
@property (nonatomic, assign) double currentLatitude;
@property (nonatomic, assign) double currentLongitute;
@property (nonatomic, strong)NSString *cityNames;
- (void)viewDidLoad {
[super viewDidLoad];
// 判断定位操作是否被允许
_manager = [[CLLocationManager alloc] init];
[_manager requestWhenInUseAuthorization];//申请定位服务权限
_manager.delegate = self;
//设置定位精度
_manager.desiredAccuracy = kCLLocationAccuracyBest;
//定位频率,每隔多少米定位一次
CLLocationDistance distance = 10.0;//十米定位一次
_manager.distanceFilter = distance;
[_manager startUpdatingLocation];
}
//代理方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
NSLog(@"定位成功");
//获取定位的坐标
CLLocation *location = [locations firstObject];
//获取坐标
CLLocationCoordinate2D coordinate = location.coordinate;
NSLog(@"定位的坐标:%f,%f", coordinate.longitude, coordinate.latitude);
_currentLongitute = coordinate.longitude;
_currentLatitude = coordinate.latitude;
[self getAddressByLatitude:_currentLatitude longitude:_currentLongitute];
//停止定位
[_manager stopUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"定位失败");
}
#pragma mark 根据坐标取得地名
-(void)getAddressByLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude{
CLGeocoder *geocoder = [[CLGeocoder alloc]init];
//反地理编码
CLLocation *location=[[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark=[placemarks firstObject];
self.cityNames =placemark.addressDictionary[@"City"];
if (self.cityNames.length == 0) {
self.cityNames = @"深圳市";
}
}];
}