iOS自带定位获取地址

引入框架

#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 = @"深圳市";

        }

        

    }];

    

}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值