计算总旅行距离iOS Swift
如何计算在Swift中使用CoreLocation的总距离
我还没有能够find任何资源如何在iOS 8的Swift中做到这一点,
你将如何计算自开始跟踪你的位置以来移动的总距离?
从我读到目前为止,我需要保存点的位置,然后计算当前点和最后一点之间的距离,然后将该距离添加到totalDistancevariables
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) }
更新: 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() } } }
示例项目
如果你想计算两点之间的路由距离 ,你需要使用MKDirectionsRequest
,这将返回一个或多个从A点到B点的路由,并带有逐步的指令:
class func caculateDistance(){ var directionRequest = MKDirectionsRequest() var sourceCoord = CLLocationCoordinate2D(latitude: -36.7346287, longitude: 174.6991812) var destinationCoord = CLLocationCoordinate2D(latitude: -36.850587, longitude: 174.7391745) var mkPlacemarkOrigen = MKPlacemark(coordinate: sourceCoord, addressDictionary: nil) var mkPlacemarkDestination = MKPlacemark(coordinate: destinationCoord, addressDictionary: nil) var source:MKMapItem = MKMapItem(placemark: mkPlacemarkOrigen) var destination:MKMapItem = MKMapItem(placemark: mkPlacemarkDestination) directionRequest.setSource(source) directionRequest.setDestination(destination) var directions = MKDirections(request: directionRequest) directions.calculateDirectionsWithCompletionHandler { (response, error) -> Void in if error != nil { println("Error calculating direction - \(error.localizedDescription)") } else { for route in response.routes{ println("Distance = \(route.distance)") for step in route.steps!{ println(step.instructions) } } } } }
这个示例代码将返回这个:
Distance Distance = 16800.0 Step by Step instructions Start on the route At the end of the road, turn left onto Bush Road Turn right onto Albany Expressway At the roundabout, take the first exit onto Greville Road toward 1, Auckland At the roundabout, take the third exit to merge onto 1 toward Auckland Keep left Take exit 423 onto Shelly Beach Road Continue onto Shelly Beach Road At the end of the road, turn right onto Jervois Road Turn left onto Islington Street Keep right on Islington Street Arrive at the destination
该function可以很容易地修改,以接收两个位置,并返回距离和任何其他所需的信息。
我希望能帮到你!
狮子座Dabus方法可以用来计算你的实际位置和开始之间的地理距离。
为了获得精确的行驶距离,您必须使用最后位置和旧位置之间的差异来更新“traveledDistance”。
这是我的实现:
var startLocation:CLLocation! var lastLocation: CLLocation! var traveledDistance:Double = 0 func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { if startLocation == nil { startLocation = locations.first as! CLLocation } else { let lastLocation = locations.last as! CLLocation let distance = startLocation.distanceFromLocation(lastLocation) startLocation = lastLocation traveledDistance += distance } }
- 如何在iOS中检查CLLocation的有效性
- 在Swift中每30分钟发送一次位置更新
- 自iOS 8以来,SignificantLocationChanges不起作用
- CLLocationManager geo-fencing / startMonitoringForRegion:vs. startMonitoringForSignificantLocationChanges:与10分钟的startUpdating调用
- iOS Swift – 用NSTimer重新加载位置function,为应用程序背景不起作用
- 位置访问 – 应用程序不要求用户访问位置的权限 – iOS 11
- CLLocation提示显示并在一瞬间消失
- locationManager:didEnterRegion和didExitRegion永远不会被调用:iBeacon
- MKCoordinateSpan和CLLocationCoordinate2D有什么区别?