1.獲取經緯度
2.經緯度轉換成地址
呼叫CLLocationManager提供的method startUpdatingLocation(),我們就能夠在CLLocationManagerDelegate的system callback didUpdateLocations中得到經緯度.
特別注意的是locationManager允許我們去設定定位的精準度,共有以下幾項:
public let kCLLocationAccuracyBestForNavigation: CLLocationAccuracy
public let kCLLocationAccuracyBest: CLLocationAccuracy
public let kCLLocationAccuracyNearestTenMeters: CLLocationAccuracy
public let kCLLocationAccuracyHundredMeters: CLLocationAccuracy
public let kCLLocationAccuracyKilometer: CLLocationAccuracy
public let kCLLocationAccuracyThreeKilometers: CLLocationAccuracy
如果我們需要的定位不用那麼精準的話,其實可以選低一點的精準度來減少獲取經緯度的時間
(a) startUpdatingLocation()
if CLLocationManager.locationServicesEnabled() {
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
(b) didUpdateLocations system callback
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
print("locations = \(locValue.latitude) \(locValue.longitude)")
self.locationManager.stopUpdatingLocation()
}
Note: 我們在didUpdateLocations這個system callback中加入**self.locationManager.stopUpdatingLocation()**來停止update location,否則ios會持續地為我們獲取經緯度,在這裡因為我們只需要一組,所以獲取後,就停止update location
前一步驟拿到經緯度後,我們利用CLGeocoder提供的reverseGeocodeLocation來把經緯度轉換成地址
let ceo: CLGeocoder = CLGeocoder()
let loc: CLLocation = CLLocation(latitude: lat, longitude: lon)
let locale = Locale(identifier: "zh_TW")
if #available(iOS 11.0, *) {
ceo.reverseGeocodeLocation(loc, preferredLocale: locale) {
(placemarks, error) in
if error == nil {
let pm = placemarks! as [CLPlacemark]
if pm.count > 0 {
let pm = placemarks![0]
print(pm.country)
print(pm.locality)
print(pm.subLocality)
print(pm.thoroughfare)
print(pm.postalCode)
print(pm.subThoroughfare)
}
}
}
}
Note1: 在上面我們再把經緯度轉換成地址前,我們還設定locale來決定轉換後地址的語系
Note2: ios 11.0以前要決定轉換後地址的語系,需要透過hard-code string key來實現,詳細code如下:
UserDefaults.standard.set(["zh_TW"], forKey: "AppleLanguages")
ceo.reverseGeocodeLocation(loc, completionHandler:
{(placemarks, error) in
UserDefaults.standard.removeObject(forKey: "AppleLanguages")
if error == nil {
let pm = placemarks! as [CLPlacemark]
if pm.count > 0 {
let pm = placemarks![0]
print(pm.country)
print(pm.locality)
print(pm.subLocality)
print(pm.thoroughfare)
print(pm.postalCode)
print(pm.subThoroughfare)
}
}
})
完整專案在以下連結:
https://github.com/tgnivekucn/GetLocation2
ref: https://www.jianshu.com/p/022a5fa58fdb