计算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

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...