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