如何计算用户在swift 3.0中从当前位置移动的距离

时间:2017-07-03 04:38:02

标签: swift core-location

我正在使用UImapkit&核心位置框架 我如何获得polyLine总距离&旅行时间

这是我的代码

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 个答案:

答案 0 :(得分:3)

您可以使用CLLocation来计算两个位置之间的距离。

let distance = newLocation.distance(from: oldLocation)

计算出距离后,您可以使用速度距离时间公式

轻松计算出行程时间
 speed = distance / time

因为你知道距离,如果你假设速度,你可以计算旅行所需的时间

 time = distance / speed

希望这些东西可以帮到你。