通过CoreLocation类,得到的定位信息都是以经度和纬度等表示的地理信息,通过CLGeocoder类可以将其反编码成一个地址。反之,也可根据一个地址获取经纬度。
1,通过经纬度获取地址
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | 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,通过地址获取经纬度
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | 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() } } |