swift 地图定位(七)地理编码与反地理编码

来源:互联网 发布:js获取微信的版本号 编辑:程序博客网 时间:2024/05/10 02:55

准备:在SB 上添加一个 UITextView 两个UITextField 两个UIButton


import UIKitimport CoreLocationclass ViewController: UIViewController {    @IBOutlet weak var addressTV: UITextView!    @IBOutlet weak var latitudeTF: UITextField!    @IBOutlet weak var longitudeTF: UITextField!        lazy var geoCoder: CLGeocoder = {        return CLGeocoder()    }()        // 地理编码  地址->经纬度    @IBAction func geoCode() {        let addressStr = addressTV.text        geoCoder.geocodeAddressString(addressStr!) { (pls: [CLPlacemark]?, error: Error?)  in            if error == nil {                print("地理编码成功")                guard let plsResult = pls else {return}                let firstPL = plsResult.first                self.addressTV.text = firstPL?.name                self.latitudeTF.text = "\((firstPL?.location?.coordinate.latitude)!)"                self.longitudeTF.text = "\((firstPL?.location?.coordinate.longitude)!)"            }else {                print("错误")            }        }    }        // 反地理编码  经纬度->地址    @IBAction func reverseGeoCode() {        let latitude = CLLocationDegrees(latitudeTF.text!) ?? 0        let longitude = CLLocationDegrees(longitudeTF.text!) ?? 0        let loc1 = CLLocation(latitude: latitude, longitude: longitude)        geoCoder.reverseGeocodeLocation(loc1) { (pls: [CLPlacemark]?, error: Error?)  in            if error == nil {                print("反地理编码成功")                guard let plsResult = pls else {return}                let firstPL = plsResult.first                self.addressTV.text = firstPL?.name                self.latitudeTF.text = "\((firstPL?.location?.coordinate.latitude)!)"                self.longitudeTF.text = "\((firstPL?.location?.coordinate.longitude)!)"            }else {                print("错误")            }        }    }}


0 0
原创粉丝点击