如何获取 iOS 中用户所在位置的经纬度

How to get latitude and longitude of a user's location in iOS

我是Swift的新人,我需要获取用户的当前位置。我的意思是我需要获取纬度和经度。我试过这个:

class ViewController: UIViewController, CLLocationManagerDelegate{

    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.startUpdatingLocation()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {

        CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error) -> Void in

            if (error != nil) {
                println("ERROR:" + error.localizedDescription)
                return
            }

            if placemarks.count > 0 {
                let pm = placemarks[0] as CLPlacemark
                self.displayLocationInfo(pm)
            } else {
                println("Error with data")
            }
        })
    }

    func displayLocationInfo(placemark: CLPlacemark) {
        //  self.locationManager.stopUpdatingLocation()

        println(placemark.locality)
        println(placemark.postalCode)
        println(placemark.administrativeArea)
        println(placemark.country)
        println(placemark.location)
    }

    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError) {
        println("Error:" + error.localizedDescription)
    }
}

在这里我可以获得坐标,但它看起来像:

<+55.75590390,+37.61744720> +/- 100.00m (speed -1.00 mps / course -1.00) @ 2/14/15, 10:48:14 AM Moscow Standard Time

如何只检索纬度和经度?

您可能会多次调用 didUpdateLocations,并且随着时间的推移准确性会提高(假设您所在的地区 GPS 信号良好 - 在室外,周围没有高楼)。您可以直接从 locations 数组中的 CLLocation 对象访问纬度和经度。

let location = locations[locations.count-1] as CLLocation;
println("\(location.latitude) \(location.longitude)");

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)

你的 locations:[AnyObject]! 实际上是一个 [CLLocation] 只需获取它的最后一个对象并使用 CLLocation 的 coordinate 属性.

https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocation_Class/index.html

已更新 Swift 3.x 和 Swift 4.x

的代码

据我所知,您在代码中使用了 print(placemark.location)

因此,如果您只想获取纬度,请使用此代码

print(placemark.location.coordinate.latitude)

如果您只想获取经度,请使用此代码

print(placemark.location.coordinate.longitude)

希望这对您有所帮助!