Through the Corelocation class, the location information obtained is the geographical information expressed in longitude and latitude, and can be deserialized into an address by the Clgeocoder class. Conversely, latitude and longitude can also be obtained according to an address.
1, get address by latitude
123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
import UIKit
import CoreLocation
import MapKit
class ViewController
:
UIViewController ,
CLLocationManagerDelegate {
@IBOutlet weak var textView:
UITextView
!
override func viewDidLoad() {
super
.viewDidLoad()
reverseGeocode()
}
//地理信息反编码
func reverseGeocode(){
var geocoder =
CLGeocoder
()
var p:
CLPlacemark
?
var currentLocation =
CLLocation
(latitude: 32.029171, longitude: 118.788231)
geocoder.reverseGeocodeLocation(currentLocation, completionHandler: {
(placemarks:[
AnyObject
]!, error:
NSError
!) ->
Void in
//强制转成简体中文
var array =
NSArray
(object:
"zh-hans"
)
NSUserDefaults
.standardUserDefaults().setObject(array, forKey:
"AppleLanguages"
)
//显示所有信息
if error !=
nil {
//println("错误:\(error.localizedDescription))")
self
.textView.text =
"错误:\(error.localizedDescription))"
return
}
let pm = placemarks
as
! [
CLPlacemark
]
if pm.count > 0{
p = placemarks[0]
as
?
CLPlacemark
//println(p) //输出反编码信息
self
.textView.text = p?.name
}
else {
println
(
"No placemarks!"
)
}
})
}
override func didReceiveMemoryWarning() {
super
.didReceiveMemoryWarning()
}
}
|
2, get latitude and longitude by address
12345678910111213141516171819202122232425262728293031323334353637383940 |
import UIKit
import CoreLocation
import MapKit
class ViewController
:
UIViewController ,
CLLocationManagerDelegate {
@IBOutlet weak var textView:
UITextView
!
override func viewDidLoad() {
super
.viewDidLoad()
locationEncode()
}
//地理信息编码
func locationEncode(){
var geocoder =
CLGeocoder
()
var p:
CLPlacemark
!
geocoder.geocodeAddressString(
"南京市新街口大洋百货"
, completionHandler: {
(placemarks:[
AnyObject
]!, error:
NSError
!) ->
Void in
if error !=
nil {
self
.textView.text =
"错误:\(error.localizedDescription))"
return
}
let pm = placemarks
as
! [
CLPlacemark
]
if pm.count > 0{
p = placemarks[0]
as
!
CLPlacemark
self
.textView.text =
"经度:\(p.location.coordinate.longitude) "
+
"纬度:\(p.location.coordinate.latitude)"
}
else {
println
(
"No placemarks!"
)
}
})
}
override func didReceiveMemoryWarning() {
super
.didReceiveMemoryWarning()
}
}
|
Swift-longitude and latitude position coordinates transform with real geographic location