计算iOS Swift的总行进距离

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

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

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

从我到目前为止所读到的,我需要保存点的位置,然后计算当前点和最后一点之间的距离,然后将该距离添加到totalDistance变量

Objective-C对我来说是非常陌生的,所以我无法解决swift语法问题

这是我到目前为止所做的,不确定我是否做得对.虽然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)



}

解决方法

更新: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()
        }
    }
}

Sample Project

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...