计算iOS Swift的总行进距离

前端之家收集整理的这篇文章主要介绍了计算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

原文链接:https://www.f2er.com/iOS/335515.html

猜你在找的iOS相关文章