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

时间:2015-02-14 07:49:52

标签: ios swift cllocationmanager cllocation

我是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)
    }
}

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

  

1 + 55.75590390,+ 37.61744720> +/- 100.00米(速度-1.00 mps /航向-1.00)@ 2/14 / 15,10:48:14 AM莫斯科标准时间

如何只检索纬度和经度?

3 个答案:

答案 0 :(得分:3)

为Swift 3.x和Swift 4.x更新了代码

我可以看到您在代码中使用了print(placemark.location)

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

print(placemark.location.coordinate.latitude)

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

print(placemark.location.coordinate.longitude)

希望这有帮助!

答案 1 :(得分:2)

您可以预期多次拨打didUpdateLocations的电话会随着时间的推移而提高准确性(假设您在GPS可以获得良好接收的本地电话 - 户外,不会被高楼包围)。您可以直接从locations数组中的CLLocation对象访问纬度和经度。

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

答案 2 :(得分:1)

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