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

4

我是一名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 (速度-1.00 mps / 路线-1.00) @ 2/14/15, 10:48:14 AM 莫斯科标准时间

我怎样才能只获取纬度和经度呢?

3个回答

3

代码已更新,适用于Swift 3.x和Swift 4.x。

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

如果你只想获取纬度,请使用以下代码:

print(placemark.location.coordinate.latitude)

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

print(placemark.location.coordinate.longitude)

希望这能有所帮助!

2

假设您所处的位置接收到良好信号(户外、没有被高楼大厦包围),您可以期望对didUpdateLocations进行多次调用,精度会随着时间改善。您可以直接从locations数组中获取CLLocation对象的纬度和经度。

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

1

现在,我需要获取最近建筑物的街道名称和门牌号码。我该如何做? - ZverArt
我不知道如何使用MapKit来实现这个,我使用Google Map SDK。你需要获取所需位置的地址(可能是CLPlaceMark?)并提取这些数据,或者它们甚至已经为您提取好了。 https://developer.apple.com/library/mac/documentation/CoreLocation/Reference/CLPlacemark_class/index.html - Pham Hoan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接