如何在Swift中使用CoreLocation计算总行驶距离
到目前为止,我还没有找到任何关于如何在iOS 8的Swift中做到这一点的资源,
您如何计算自开始跟踪位置以来移动的总距离?
从我所读到的到目前为止,我需要保存一个点的位置,然后计算当前点和最后一个点之间的距离,然后将该距离添加到totalDistance变量
Objective-C对我来说是非常陌生的,所以我还没有能够解决Swift语法
下面是我目前为止所做的工作,不确定我做的是否正确。
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var newLocation: CLLocation = locations[0] as CLLocation
oldLocationArray.append(newLocation)
var totalDistance = CLLocationDistance()
var oldLocation = oldLocationArray.last
var distanceTraveled = newLocation.distanceFromLocation(oldLocation)
totalDistance += distanceTraveled
println(distanceTraveled)
}
3条答案
按热度按时间nhaq1z211#
更新:Xcode 8.3.2 · Swift 3.1
问题是你总是一遍又一遍地得到相同的位置。试试这样:
Sample Project
wn9m85ua2#
如果您要计算两点之间的路径距离,则需要使用
MKDirectionsRequest
,这将返回一条或多条从A点到B点的路径,其中包含分步说明:此示例代码将返回以下内容:
该函数可以很容易地修改为接收两个位置并返回距离和任何其他所需的信息。
希望对你有帮助!
jfgube3f3#
Leo Dabus方法可用于计算您的实际位置与开始位置之间的地理距离。
为了获得精确的行驶距离,您必须使用最后一个位置和旧位置之间的差异来更新“traveledDistance”。
这是我的实现: