在Xcode的CLLocationManager中调用行驶总距离计算函数的问题
解决CLLocationManager中调用行驶距离计算函数的问题
我来帮你一步步理清怎么调用教授提供的计算总行驶距离的函数,从基础准备到实际调用拆解清楚:
1. 先准备必要的存储变量
首先在你的类(比如ViewController或者专门的位置管理类)里添加两个核心属性,用来记录计算所需的依赖数据:
// 存储累计的总行驶距离(单位:米) private var totalTraveledDistance: CLLocationDistance = 0.0 // 记录上一次获取到的有效位置,用于和当前位置计算距离差 private var lastValidLocation: CLLocation?
2. 理解教授函数的参数逻辑
虽然你没给出教授函数的具体代码,但这类计算行驶距离的函数通常有两种常见形式,对应不同的调用方式:
形式一:计算两个位置的单次距离(返回距离值)
教授的函数可能是这样的,接收两个CLLocation参数,返回两点间的直线距离:
func calculateSingleDistance(from start: CLLocation, to end: CLLocation) -> CLLocationDistance { return start.distance(from: end) }
调用时,你需要传入上一次的有效位置和当前最新位置,再把返回的距离累加到总距离里。
形式二:直接更新总距离(带inout参数)
另一种可能是教授的函数直接帮你处理累加逻辑,这时它会接收当前位置、上一次位置,以及一个用于修改的总距离参数:
func updateTotalTravelDistance(currentLoc: CLLocation, lastLoc: CLLocation?, totalDistance: inout CLLocationDistance) { guard let lastLocation = lastLoc else { return } let distance = lastLocation.distance(from: currentLoc) totalDistance += distance }
3. 在didUpdateLocations中实际调用
在位置更新的回调里,先筛选出有效的最新位置,再根据教授函数的形式调用:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { // 取数组中最新的位置(locations数组最后一个元素是最新的) guard let currentLocation = locations.last else { return } // 过滤掉精度不合格的位置(避免无效数据干扰计算) guard currentLocation.horizontalAccuracy > 0 else { return } // ---------- 调用教授的函数 ---------- // 如果是形式一:计算单次距离再累加 if let lastLoc = lastValidLocation { let singleDistance = calculateSingleDistance(from: lastLoc, to: currentLocation) totalTraveledDistance += singleDistance // 这里可以打印或更新UI展示总距离 print("当前总行驶距离:\(totalTraveledDistance) 米") } // 如果是形式二:直接调用更新总距离的函数 updateTotalTravelDistance(currentLoc: currentLocation, lastLoc: lastValidLocation, totalDistance: &totalTraveledDistance) // 更新上一次的有效位置,供下一次计算使用 lastValidLocation = currentLocation // 你原来的位置坐标处理逻辑可以继续保留 let locValue = currentLocation.coordinate print("当前位置:纬度\(locValue.latitude),经度\(locValue.longitude)") }
4. 额外注意事项
- 确保你已经在Info.plist中配置了位置权限描述(
NSLocationWhenInUseUsageDescription或NSLocationAlwaysAndWhenInUseUsageDescription),并且正确请求了权限 - 根据你的场景设置合适的精度,比如导航场景用
kCLLocationAccuracyBestForNavigation,普通场景用kCLLocationAccuracyHundredMeters - 如果需要重置总距离,直接把
totalTraveledDistance设为0,同时把lastValidLocation置为nil即可
内容的提问来源于stack exchange,提问作者Caleb Bartholomew
相关产品推荐
相关产品推荐

