【发布时间】:2019-07-30 11:49:46
【问题描述】:
我有一个应用程序,可以像 Uber 应用程序一样计算行驶距离。当驾驶员开始旅行时,即使在搜索行程中指定了起点,位置也开始发生变化,驾驶员可能会决定通过替代路线或通过较长的地方和路线,因为他/她不知道最短路线,那么我如何计算总距离。
起始位置是司机点击开始按钮的位置 结束位置是司机按下停止按钮的位置
这是我目前的代码
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
lastLocation = locations.last!
endTrip(locations.last)
if !hasSetInitialLocation {
let camera = GMSCameraPosition.camera(withTarget: lastLocation!.coordinate, zoom: 17)
self.mapView.animate(to: camera)
hasSetInitialLocation = true
endTrip(lastLocation)
MqttManager.instance.connectToServer()
}
}
func endTrip(endLoaction: CLLocation) {
guard let statusChange = source.getStatusChange() else{return}
var distanceTraveled: Double = 0.0
let initialLocation = CLLocation(latitude: (statusChange.meta?.location?.lat)!, longitude: (statusChange.meta?.location?.lng)!)
let distance = initialLocation.distance(from: endLoaction)
distanceTraveled += distance
let distanceInKM = Utility.convertCLLocationDistanceToKiloMeters(targetDistance: distanceTraveled)
}
我如何计算距离以反映驾驶员移动的总距离,因为从建议的起点和终点的路线可能会发生变化。
司机按下了一个叫做start trip的按钮,我想得到从那一刻到他按下按钮end trip的那一刻的距离
这个实现可以从类似的工作代码中获得,但唯一的区别是它们是一个开始按钮,它传递该点的坐标和一个停止坐标,它是坐标的结束。
enum DistanceValue: Int {
case meters, miles
}
func calculateDistanceBetweenLocations(_ firstLocation: CLLocation, secondLocation: CLLocation, valueType: DistanceValue) -> Double {
var distance = 0.0
let meters = firstLocation.distance(from: secondLocation)
distance += meters
switch valueType {
case .meters:
return distance
case .miles:
let miles = distance
return miles
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if startLocation == nil {
startLocation = locations.first
} else if let location = locations.last {
runDistance += lastLocation.distance(from: location)
let calc = calculateDistanceBetweenLocations(lastLocation, secondLocation: location, valueType: .meters)
print("TOTAL LOC 1 \(calc)")
print("TOTAL LOC 2 \(runDistance)")
}
lastLocation = locations.last
}
如我的打印声明中所示print("TOTAL LOC 1 \(calc)")
print("TOTAL LOC 2 \(runDistance)") 我该怎么做
calc同runDistance
这是控制台中打印的内容
TOTAL LOC 10.29331530774379
TOTAL LOC 2 10.29331530774379
TOTAL LOC 2.2655118031831587
TOTAL LOC 2 12.558827110926948
【问题讨论】:
-
但是你的问题是什么?
-
如何计算距离以反映司机移动的总距离
-
不就是用
CLLocationDistance和CLLocationCoordinate2D连接位置点,计算整个距离吗? -
我猜你需要经常检查当前位置并将其与前一个位置进行比较并将距离添加到总距离
-
@ElTomato 但是如果你绕着街区开一圈,行程有多远?也许是一个哲学问题:)?
标签: ios swift cllocationmanager cllocation cllocationdistance