简体   繁体   English

快速获取行进的总距离ios 9

[英]Swift Getting total distance traveled ios 9

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
}

I found the code above on stackoverflow and its working if i drive or walk in one direction but when i turn around and go back to the start point the distane is 0m.it would be nice if someone could explain the code in detail or give me some advice. 我在上面的代码中找到了stackoverflow上的代码,并且如果我向一个方向行驶或步行,它也可以正常工作,但是当我转身回到起点时,距离为0m。如果有人可以详细解释代码或给我,那将是很好的一些忠告。 thanks 谢谢

Isn't it trivial? 这不是小事吗? You are printing the distance which is calculated over and over from the startLocation which will never change in your code. 您正在打印从startLocation计算的distance ,该distance在您的代码中永远不会改变。 If I start in point A and go to B (there will be some distance in meters) and then go back to A and calculate from the startLocation (which is always A ) it should be zero. 如果我从点A开始,然后转到B (会有一些距离,以米为单位),然后返回A ,然后从startLocation (始终为A )进行计算,则该值应为零。 :D :D

I didn't try your code but it seems to me this is what happens there. 我没有尝试您的代码,但在我看来这就是那里发生的情况。 Print traveledDistance instead, this is the value that will always increase as you move around. 而是打印traveledDistance ,这是您随处移动时将始终增加的值。

Fix your code like this: 像这样修复您的代码:

print("\(traveledDistance)")
distanceLabel.text = "\(traveledDistance)"

If you only need the total distance I would change the code to look like this: 如果您只需要总距离,则可以将代码更改为如下所示:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM