iOS 系统定位具体到省市区街道


iOS系统自带定位,用CLLocationManager就可以轻松的实现定位的操作,获得的是一组经纬度,当然,也可以根据给出的经纬度获取相应的省份、城市、街道等信息,下面就看一个根据经纬度获得城市的demo;(无聊研究的,仅供参考)

副本主要任务

  • 定位设备经纬度与所在城市

预备知识-CLLocation对象(可跳过)

CLLocation对象存储着CLLocationManager对象生成的位置数据,先介绍一下它的属性大概了解CLLocation是什么东西

用于定位的属性 含义
coordinate 地理位置(经纬度)
altitude 海拔
floor 建筑内逻辑楼层
timestamp 定位时间戳
horizontalAccuracy 水平技能范围,单位米(见注1)
verticalAccuracy 海拔误差,单位米

注1:我们在地图上的点由经度和纬度确定,horizontalAccuracy表示该圆的半径是多大(单位为米),负值表示该点无效(经常用在if语句中判断点是否可用)

用于速度和方向的属性 含义
speed 瞬时速度
course 设备移动方向

 

 

2.获取经纬度

2.1 iOS8前的BUG

我们需要在info.plist文件里添加两个字段给APP定位权限,不然在iOS8后是无法启动定位的。他们分别是

属性名 含义
NSLocationWhenInUseUsageDescription 使用期间
NSLocationAlwaysUsageDescription 始终开启

添加如下:


 

上个效果图好理解点:


 



- (void)findCurrentLocation { self.isFirstUpdate = YES; // 1 if (! [CLLocationManager locationServicesEnabled]) { [TSMessage showNotificationWithTitle:@"未开启定位服务" subtitle:@"请开启定位服务定位您所在城市." type:TSMessageNotificationTypeError]; } // 2 else if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) { [self.locationManager requestWhenInUseAuthorization]; [self.locationManager startUpdatingLocation]; } // 3 else { [self.locationManager requestAlwaysAuthorization]; [self.locationManager startUpdatingLocation]; } } - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations { if (self.isFirstUpdate) { // 4 self.isFirstUpdate = NO; return; } // 5 CLLocation *newLocation = [locations lastObject]; self.currentLocation = newLocation; CLGeocoder *geocoder = [[CLGeocoder alloc] init]; // 反向地理编译出地址信息 [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) { if (! error) { if ([placemarks count] > 0) { CLPlacemark *placemark = [placemarks firstObject]; // 获取城市 NSString *city = placemark.locality; if (! city) { // 6 city = placemark.administrativeArea; } self.currentCity = city; } else if ([placemarks count] == 0) { [TSMessage showNotificationWithTitle:@"GPS故障" subtitle:@"定位城市失败" type:TSMessageNotificationTypeError]; } } else { [TSMessage showNotificationWithTitle:@"网络错误" subtitle:@"请检查您的网络" type:TSMessageNotificationTypeError]; } }]; [self.locationManager stopUpdatingLocation]; }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM