【问题标题】:Distance isn't being calculated in Swift 3Swift 3 中没有计算距离
【发布时间】:2017-03-07 21:15:44
【问题描述】:

我正在尝试使用 CLLocationManager 计算行进距离并显示标签内的距离。请求使用位置有效,但标签中未显示任何内容。我曾尝试在 xCode 模拟器中模拟驱动器,但无济于事。我在应用程序中显示了一张地图,它可以跟踪我的位置,但仅此而已。

这是我的 locationManager 方法:

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

    // Map

    theLabel.text = "\(locations[0])"
    myLocations.append(locations[0] as! CLLocation)

    let spanX = 0.007
    let spanY = 0.007
    let newRegion = MKCoordinateRegion(center: theMap.userLocation.coordinate, span: MKCoordinateSpanMake(spanX, spanY))
    theMap.setRegion(newRegion, animated: true)

    if (myLocations.count > 1){
        let sourceIndex = myLocations.count - 1
        let destinationIndex = myLocations.count - 2

        let c1 = myLocations[sourceIndex].coordinate
        let c2 = myLocations[destinationIndex].coordinate
        var a = [c1, c2]
        let polyline = MKPolyline(coordinates: &a, count: a.count)
        theMap.add(polyline)
    }

    // Labels

    let latestLocation: AnyObject = locations[locations.count - 1]
    lat.text = String(format: "%.4f", latestLocation.coordinate.latitude)
    long.text = String(format: "%.4f", latestLocation.coordinate.longitude)
    horizAcc.text = String(format: "%.4f", latestLocation.horizontalAccuracy)
    altitude.text = String(format: "%.4f", latestLocation.altitude)
    vertAcc.text = String(format: "%.4f", latestLocation.verticalAccuracy)

    if startLocation == nil {
        startLocation = latestLocation as! CLLocation
    }

    let distanceBetween = (latestLocation.distance(from: startLocation))

    distance.text = String(format: "%.2f", distanceBetween)

}

非常感谢任何帮助!如果需要,我可以提供更多代码。

【问题讨论】:

  • 你能描述一下到底是什么不工作吗?说“这就是全部”
  • 我正在计算距离并将其放入标签中,但标签永远不会改变。
  • 最后做print(distanceBetween)并告诉输出
  • 通过使用 print 语句我已经确定代码永远不会到达 locationManager 方法,我做错了什么?
  • 当您创建您的位置管理器时,您是否设置了它的委托?

标签: ios swift location cllocationmanager distance


【解决方案1】:

听起来您没有为CLLocationManager 的实例正确设置委托属性。您需要让它知道哪个对象包含您对 CLLocationManagerDelegate 方法的实现,就像您列出的那样。

因此,假设您的视图控制器符合 CLLocationManagerDelegate 并包含您发布的方法,并假设您已为视图控制器提供名为“locationManager”的 CLLocationManager 属性,您只需像这样进行设置:

    self.locationManager.delegate = self
    self.locationManager.startUpdatingLocation()

您可以将它放在 viewDidLoad: 或任何适合您需要的地方,并且应该调用您的 didUpdateLocation 委托方法。

【讨论】:

    猜你喜欢
    • 2016-12-24
    • 2017-03-04
    • 2023-03-16
    • 1970-01-01
    • 2015-05-11
    • 1970-01-01
    • 1970-01-01
    • 2014-06-29
    • 1970-01-01
    相关资源
    最近更新 更多