小编典典

计算总行进距离iOS Swift

swift

如何在Swift中使用CoreLocation计算行进的总距离

到目前为止,我还无法找到有关如何在iOS 8的Swift中执行此操作的任何资源。

自开始跟踪位置以来,您将如何计算移动的总距离?

根据到目前为止的读物,我需要保存一个点的位置,然后计算当前点与最后一个点之间的距离,然后将该距离添加到totalDistance变量中

Objective-C对我来说是非常陌生的,所以我还无法计算出快速的语法

这是我到目前为止已经完成的工作,不确定我是否做对了。尽管该distanceFromLocation方法返回的都是0.0,所以很明显有些错误

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
     var newLocation: CLLocation = locations[0] as CLLocation

    oldLocationArray.append(newLocation)
           var totalDistance = CLLocationDistance()
    var oldLocation = oldLocationArray.last

    var distanceTraveled = newLocation.distanceFromLocation(oldLocation)

    totalDistance += distanceTraveled

 println(distanceTraveled)



}

阅读 295

收藏
2020-07-07

共1个答案

小编典典

更新: Xcode 8.3.2•Swift 3.1

那里的问题是因为您总是一遍又一遍地获得相同的位置。尝试这样:

import UIKit
import MapKit

class ViewController: UIViewController,  CLLocationManagerDelegate {
    @IBOutlet weak var mapView: MKMapView!
    let locationManager = CLLocationManager()
    var startLocation: CLLocation!
    var lastLocation: CLLocation!
    var startDate: Date!
    var traveledDistance: Double = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.requestWhenInUseAuthorization()
            locationManager.startUpdatingLocation()
            locationManager.startMonitoringSignificantLocationChanges()
            locationManager.distanceFilter = 10
            mapView.showsUserLocation = true
            mapView.userTrackingMode = .follow
        }
    }
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if startDate == nil {
            startDate = Date()
        } else {
            print("elapsedTime:", String(format: "%.0fs", Date().timeIntervalSince(startDate)))
        }
        if startLocation == nil {
            startLocation = locations.first
        } else if let location = locations.last {
            traveledDistance += lastLocation.distance(from: location)
            print("Traveled Distance:",  traveledDistance)
            print("Straight Distance:", startLocation.distance(from: locations.last!))
        }
        lastLocation = locations.last
    }
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        if (error as? CLError)?.code == .denied {
            manager.stopUpdatingLocation()
            manager.stopMonitoringSignificantLocationChanges()
        }
    }
}

样例项目

2020-07-07