func locationManager(manager: CLLocationManager, didUpdateLocations locations: [AnyObject]){
if startLocation == nil {
startLocation = locations.first as! CLLocation
}
else{
let distance = startLocation.distanceFromLocation(locations.last as! CLLocation)
let lastDistance = lastLocation.distanceFromLocation(locations.last as! CLLocation)
traveledDistance += lastDistance
//print("\(startLocation)")
//print("\(lastLocation)")
//print("\(traveledDistance)")
print("\(distance)")
distanceLabel.text = "\(distance)"
}
lastLocation = locations.last as! CLLocation
}
我在stackoverflow上找到了上面的代码,如果我开车或朝一个方向行走,但是当我转身回到起点时,distane是0m。如果有人可以详细解释代码,那将会很好或者给我一些建议。 感谢
答案 0 :(得分:2)
这不是微不足道的吗?您正在打印从distance
反复计算的startLocation
,它将永远不会在您的代码中发生变化。如果我从点A
开始并转到B
(以米为单位会有一些距离),然后返回A
并从startLocation
计算(这总是A
)它应该为零。 :D
我没有尝试你的代码,但在我看来这就是那里发生的事情。相反,请打印traveledDistance
,这是随着您移动时总是会增加的值。
修复你的代码:
print("\(traveledDistance)")
distanceLabel.text = "\(traveledDistance)"
如果您只需要总距离,我会将代码更改为:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [AnyObject]) {
/* for the ever first call the if check should fail because lastLocation is initially nil in your code (I assume) */
if lastLocation != nil {
/* this will start adding a distance at the second call of the callback */
traveledDistance += lastLocation.distanceFromLocation(locations.last as! CLLocation)
print("\(traveledDistance)")
distanceLabel.text = "\(traveledDistance)"
}
/* here we are saving the current location to our variable for later calculation */
lastLocation = locations.last as! CLLocation
}