How to calculate the distance travelled by user from current location in swift 3.0

天涯浪子 提交于 2019-12-25 08:38:15

问题


I am using UImapkit & core location frameworks How will I get the total polyLine distance & travelled time

this my code

func locationManager(_ manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {



      if let oldLocationNew = oldLocation as CLLocation?{
        let oldCoordinates = oldLocationNew.coordinate


        let newCoordinates = newLocation.coordinate
        var area = [oldCoordinates, newCoordinates]
        print(area)
        let polyline = MKPolyline(coordinates: &area, count: area.count)
        mkMapView.add(polyline)


    }

//calculation for location selection for pointing annoation
    if (previousLocation as CLLocation?) != nil{

        if previousLocation.distance(from: newLocation) > 10 {
            addAnnotationsOnMap(newLocation)
            previousLocation = newLocation
        }
    }else{
        //case if previous location doesn't exists
        addAnnotationsOnMap(newLocation)
        previousLocation = newLocation
    }
}

回答1:


You can use CLLocation to calculate the distance between two locations.

i.e

let distance = newLocation.distance(from: oldLocation)

Once you calculated the distance, then you can easily calculate the travel time by using the speed distance time formula

 speed = distance / time

since you know the distance and if you assume the speed, you can calculate time taken for the travel as

 time = distance / speed

Hope this stuff will help you.



来源:https://stackoverflow.com/questions/44877908/how-to-calculate-the-distance-travelled-by-user-from-current-location-in-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!