如何从坐标数组计算平均速度?附Android位置采集代码片段
如何从LatLng坐标数组计算平均速度?
嘿,我来帮你搞定这个问题!首先得明确:平均速度的核心逻辑是总路程 ÷ 总时间,但你当前的代码只存储了LatLng坐标,缺少每个位置对应的时间戳——这是计算速度的关键信息,所以我们得先调整数据存储方式,再一步步实现计算逻辑。
第一步:修改数据结构,存储带时间的位置记录
我们需要一个自定义类来同时保存坐标和时间戳,替换原来单纯的ArrayList<LatLng>:
// 自定义数据类,封装坐标与对应的时间戳 public class LocationRecord { public LatLng latLng; public long timestamp; // 时间戳单位:毫秒 public LocationRecord(LatLng latLng, long timestamp) { this.latLng = latLng; this.timestamp = timestamp; } } // 替换原来的全局变量points ArrayList<LocationRecord> locationRecords = new ArrayList<>();
第二步:在位置更新时记录时间戳
在onLocationChanged方法里,把当前位置的时间戳(通过Location.getTime()获取)和坐标一起存入列表:
public void onLocationChanged(final Location location) { LatLng myCoordinates = new LatLng(location.getLatitude(), location.getLongitude()); // 创建带时间戳的位置记录并加入列表 LocationRecord record = new LocationRecord(myCoordinates, location.getTime()); locationRecords.add(record); // 你原来的UI操作保持不变 LocationMarker.setPosition(myCoordinates); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myCoordinates, 15)); }
第三步:实现平均速度计算方法
现在我们可以遍历记录列表,累加总路程和总时间,最后计算平均速度:
/** * 计算平均速度,默认返回单位为 米/秒 * 若需要转换为 公里/小时,只需将结果乘以3.6即可 * @return 平均速度,当记录不足2条时返回0 */ public double calculateAverageSpeed() { // 至少需要2个位置记录才能计算速度 if (locationRecords.size() < 2) { return 0.0; } double totalDistance = 0.0; long totalTimeMillis = 0; // 遍历所有相邻位置,累加路程与时间差 for (int i = 0; i < locationRecords.size() - 1; i++) { LocationRecord current = locationRecords.get(i); LocationRecord next = locationRecords.get(i + 1); // 使用Android系统API计算两个经纬度间的地表距离(单位:米) float[] distanceResult = new float[1]; Location.distanceBetween( current.latLng.latitude, current.latLng.longitude, next.latLng.latitude, next.latLng.longitude, distanceResult ); totalDistance += distanceResult[0]; // 累加相邻记录的时间差(单位:毫秒) totalTimeMillis += next.timestamp - current.timestamp; } // 避免除以0的异常情况 double totalTimeSeconds = totalTimeMillis / 1000.0; if (totalTimeSeconds <= 0) { return 0.0; } // 计算平均速度:总路程 ÷ 总时间(米/秒) double averageSpeedMps = totalDistance / totalTimeSeconds; // 可选:转换为公里/小时 // double averageSpeedKmph = averageSpeedMps * 3.6; return averageSpeedMps; }
关键注意点
- 为什么用
Location.distanceBetween?这个API是Android系统提供的,会考虑地球曲率,比自己手动用经纬度公式计算的结果更准确。 - 边界处理:当位置记录少于2条、或者总时间为0时,直接返回0,避免出现计算异常。
- 单位转换:如果需要常用的公里/小时,只需把米/秒的结果乘以3.6即可。
内容的提问来源于stack exchange,提问作者JamesD
相关产品推荐
相关产品推荐

