【问题标题】:Core location returning 0 as altitude核心位置返回 0 作为高度
【发布时间】:2017-04-20 00:35:15
【问题描述】:

看这里Finding Altitude in Swift 看看我的代码

import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    @IBOutlet weak var lbl: UILabel!
    var player: AVAudioPlayer?

    var locationManager:CLLocationManager = CLLocationManager()

    var alt: Double?

    @IBOutlet weak var coor: UILabel!

    func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {
        alt = newLocation.altitude
        var altitude = locationManager.location?.altitude
        print("\(altitude)")
        manager.stopUpdatingLocation()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.locationManager = CLLocationManager()
        locationManager.requestWhenInUseAuthorization()
        self.locationManager.delegate = self
        self.locationManager.distanceFilter = kCLDistanceFilterNone
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.startUpdatingLocation()
    }

    @IBAction func getCoor(_ sender: Any) {
        var altitude = locationManager.location?.altitude
        coor.text = "\(altitude)"
    }
}

为什么它不显示实际高度而是总是显示 0.0?

【问题讨论】:

  • 你的海拔是多少?它返回什么纬度和经度?位置为零吗?真的有位置吗?您是否在模拟器上的设备上运行?
  • 是swift 3吗?
  • 您实现了CLLocationManagerDelegate 协议吗?我的意思是......保存每个并发位置?每次位置更新都会更加准确。
  • 你是在真机而不是模拟器上测试吗?另外,您有位置(纬度/经度)吗?

标签: swift swift3 core-location


【解决方案1】:

这样的代码注定失败:

func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {
    // ...
    manager.stopUpdatingLocation()
}

使用startUpdatingLocation 启动位置管理器后,您将在第一次调用didUpdateLocation 时停止位置管理器。但是第一次调用总是假的,甚至接下来的十几次调用也可能只是热身,因为硬件得到了修复。

如果您的问题是“我在哪里”,请使用requestLocation,而不是startUpdatingLocation。它只调用一次didUpdateLocation,并且只有在它确实确实有足够好的位置(这可能需要一些时间)时。

最后,请注意,您的代码在 Swift 3 中不正确。locationManager(manager:...)永远被调用。 Read the docs 学习正确的签名。

【讨论】:

    【解决方案2】:

    您将 newlocation.altitude 存储到“alt”变量中,但打印“altitude”。

    试试:print("\(alt)")

    【讨论】:

      猜你喜欢
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多