在獲取用戶位置時候煮盼,Core Location 會返回一對經(jīng)緯度漾橙。我們?nèi)祟惪床怀鍪裁礀|東婶恼,但是存在就是合理,交給機(jī)器吧畅涂。
地理編碼 : 地址 -> 坐標(biāo)
反地理編碼: 坐標(biāo) (經(jīng)緯度) -> 地址
Core Location 提供了轉(zhuǎn)換工具港华,但需要聯(lián)網(wǎng)(;′⌒`)
Core Location 通過 CLGeocoder 類來實(shí)現(xiàn)正向和反向地理編碼午衰,因?yàn)槭峭ㄟ^服務(wù)器來實(shí)現(xiàn)轉(zhuǎn)換的立宜,所以得聯(lián)網(wǎng)。
在進(jìn)行反地理編碼時候臊岸,會返回一個數(shù)組橙数。其中包含很多 CLPlacemark 對象。為啥是數(shù)組呢帅戒,因?yàn)榉吹乩砭幋a解析時候灯帮,可能會反回許多可能的值崖技。
可以訪問的屬性有:
? 位置的名字
? 街道名稱
? 地區(qū)
? 子地區(qū)
? 行政區(qū)域
? 子行政區(qū)域
? 郵政編碼
? 國家代碼
? 國家名字
-有些地方,可能還包含其他相關(guān)信息
我們可以利用上面需要的信息钟哥,生成用戶需要的字符串迎献。
//1 import CoreLocation 2 CLLocationManagerDelegate
//反地理編碼
func reverseGeocode(latitude:Double, longitude: Double){
let geocoder = CLGeocoder()
let currentLocation = CLLocation(latitude: latitude, longitude: longitude)
geocoder.reverseGeocodeLocation(currentLocation, completionHandler: {
(placemarks:[CLPlacemark]?, error:NSError?) -> Void in
guard error == nil else {
return print(error!.localizedDescription)
}
guard let p = placemarks?[0] else {
return print("沒有找到一個地址")
}
print(p.name) // 中國廣東省廣州市XX區(qū)XX街道幾號
/*
name // eg. Apple Inc.
thoroughfare // street name, eg. Infinite Loop
subThoroughfare // eg. 1
locality // city, eg. Cupertino
subLocality // neighborhood, common name, eg. Mission District
administrativeArea // state, eg. CA
subAdministrativeArea // county, eg. Santa Clara
postalCode // zip code, eg. 95014
ISOcountryCode // eg. US
country // eg. United States
inlandWater // eg. Lake Tahoe
ocean // eg. Pacific Ocean
areasOfInterest // eg. Golden Gate Park
*/
})
}
//地理編碼
func locationEncode() {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString("廣州塔", completionHandler: {
(placemarks:[CLPlacemark]?, error:NSError?) -> Void in
guard error == nil else {
return print(error!.localizedDescription)
}
guard let p = placemarks?[0] else {
return print("沒有找到一個地址")
}
let longitude = p.location?.coordinate.longitude
let latitude = p.location?.coordinate.latitude
print("經(jīng)度:\(longitude),維度:\(latitude)")
})
}