You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter/Dart中如何计算排除最后一个元素的LatLng列表平均坐标

多边形坐标平均点计算方案

问题描述

拥有一组LatLng坐标列表,列表最后一个元素与第一个元素始终相同(构成闭合多边形),需要编写通用函数计算并返回除最后一个元素外所有坐标的平均经纬度。原实现仅能处理固定长度列表,无法适配更长的坐标序列,期望得到的平均坐标为:

LatLng(50.08110015101990, 8.24277162551880)

解决方案

通用实现代码

LatLng calculateAverageCoordinate(List<LatLng> coordinates) {
  // 处理边界情况:列表长度不足2(至少需要首尾两个重复元素)
  if (coordinates.length <= 1) {
    throw ArgumentError('坐标列表至少需要包含2个元素(首尾重复)');
  }

  double totalLatitude = 0.0;
  double totalLongitude = 0.0;
  // 有效坐标数量:总长度减1(排除最后一个重复的元素)
  final validCoordinateCount = coordinates.length - 1;

  // 遍历所有有效坐标,累加经纬度总和
  for (int i = 0; i < validCoordinateCount; i++) {
    final currentCoord = coordinates[i];
    totalLatitude += currentCoord.latitude;
    totalLongitude += currentCoord.longitude;
  }

  // 计算平均值
  final averageLatitude = totalLatitude / validCoordinateCount;
  final averageLongitude = totalLongitude / validCoordinateCount;

  return LatLng(averageLatitude, averageLongitude);
}

调用示例

final listOfLatLngs = [
  const LatLng(50.08155798581401, 8.24199914932251),
  const LatLng(50.08053216096673, 8.242063522338867),
  const LatLng(50.080614778545716, 8.243619203567505),
  const LatLng(50.0816956787534, 8.243404626846313),
  const LatLng(50.08155798581401, 8.24199914932251),
];

void main() {
  try {
    final averageCoord = calculateAverageCoordinate(listOfLatLngs);
    print(averageCoord); // 输出目标结果:LatLng(50.08110015101990, 8.24277162551880)
  } catch (e) {
    print(e);
  }
}

关键优化点

  • 不修改原列表:避免使用removeLast()修改输入列表,通过遍历到length-1的位置处理有效坐标,保证原数据的完整性。
  • 完全通用性:函数接收列表参数,支持任意长度的符合规则的坐标列表(只要首尾重复)。
  • 边界安全:加入长度判断,防止因空列表或无效列表导致的除以0异常。
  • 高效计算:单次循环累加经纬度,时间复杂度为O(n),性能最优。

内容的提问来源于stack exchange,提问作者OverdoseB12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 17:18:21