📜  我的位置是什么 (1)

📅  最后修改于: 2023-12-03 15:39:39.430000             🧑  作者: Mango

我的位置是什么

本文将介绍如何获取当前设备的位置信息,并返回经纬度坐标和地址信息。

实现步骤
  1. 导入定位服务
import CoreLocation
  1. 创建CLLocationManager对象
let locationManager = CLLocationManager()
  1. 请求定位权限
// 请求一次定位权限
locationManager.requestWhenInUseAuthorization()

// 请求始终定位权限
locationManager.requestAlwaysAuthorization()
  1. 设置CLLocationManagerDelegate
locationManager.delegate = self
  1. 实现CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    // 获取当前位置
    let location = locations.first
    // 获取经纬度坐标
    let coordinate = location?.coordinate
    // 获取地址信息
    CLGeocoder().reverseGeocodeLocation(location!, completionHandler: { (placemarks, error) in
        if error == nil {
            let placemark = placemarks?.first
            // 获取地址字符串
            let address = "\(placemark?.country ?? ""), \(placemark?.locality ?? ""), \(placemark?.subLocality ?? ""), \(placemark?.thoroughfare ?? ""), \(placemark?.subThoroughfare ?? "")"
            print("经度:\(coordinate!.longitude), 纬度:\(coordinate!.latitude), 地址:\(address)")
        } else {
            print(error?.localizedDescription ?? "")
        }
    })
}
  1. 请求定位
locationManager.startUpdatingLocation()
完整代码
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        // 请求一次定位权限
        locationManager.requestWhenInUseAuthorization()

        // 设置CLLocationManagerDelegate
        locationManager.delegate = self

        // 开始定位
        locationManager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        // 获取当前位置
        let location = locations.first
        // 获取经纬度坐标
        let coordinate = location?.coordinate
        // 获取地址信息
        CLGeocoder().reverseGeocodeLocation(location!, completionHandler: { (placemarks, error) in
            if error == nil {
                let placemark = placemarks?.first
                // 获取地址字符串
                let address = "\(placemark?.country ?? ""), \(placemark?.locality ?? ""), \(placemark?.subLocality ?? ""), \(placemark?.thoroughfare ?? ""), \(placemark?.subThoroughfare ?? "")"
                // 打印位置信息
                print("经度:\(coordinate!.longitude), 纬度:\(coordinate!.latitude), 地址:\(address)")
            } else {
                print(error?.localizedDescription ?? "")
            }
        })
    }
}
结语

通过上述步骤,即可获取设备当前位置的经纬度坐标和地址信息。