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

基于React计算多个坐标点间的海里距离方法问询

在React中计算多个坐标点间的海里距离

要计算给定坐标数组中相邻点的总海里距离,可通过以下步骤实现:

1. 实现两点间海里距离计算函数

使用Haversine公式计算球面两点间的距离,适配海里单位:

// 角度转弧度工具函数
const degreesToRadians = degrees => degrees * Math.PI / 180;

// 计算两点间的海里距离
const getNauticalDistance = (lat1, lon1, lat2, lon2) => {
  const earthRadiusNm = 3440; // 地球半径(海里)
  const dLat = degreesToRadians(lat2 - lat1);
  const dLon = degreesToRadians(lon2 - lon1);

  const a = 
    Math.sin(dLat / 2) ** 2 +
    Math.cos(degreesToRadians(lat1)) * Math.cos(degreesToRadians(lat2)) *
    Math.sin(dLon / 2) ** 2;
  
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  return parseFloat((earthRadiusNm * c).toFixed(2)); // 保留两位小数
};

2. 遍历坐标数组计算总距离

遍历数组,累加每一对相邻点的距离:

// 计算坐标数组的总海里距离
const calculateTotalNauticalDistance = points => {
  if (points.length < 2) return 0;
  
  let total = 0;
  for (let i = 0; i < points.length - 1; i++) {
    const curr = points[i];
    const next = points[i + 1];
    total += getNauticalDistance(curr.lat, curr.long, next.lat, next.long);
  }
  return parseFloat(total.toFixed(2));
};

3. 在React组件中使用

将上述函数整合到React组件中,处理你的坐标数据:

import React from 'react';

// 插入上面的工具函数

const DistanceCalculator = () => {
  // 替换为你的实际经纬度数据
  const calculateDistance = [
    {point_id: 1, long: -122.4194, lat: 37.7749},
    {point_id: 2, long: -118.2437, lat: 34.0522},
    {point_id: 3, long: -74.0060, lat: 40.7128},
    {point_id: 4, long: -0.1278, lat: 51.5074},
    {point_id: 5, long: 139.6917, lat: 35.6895},
  ];

  const totalDistance = calculateTotalNauticalDistance(calculateDistance);

  return (
    <div className="distance-calculator">
      <h2>总航行距离:{totalDistance} 海里</h2>
      <h3>各段距离:</h3>
      <ul>
        {calculateDistance.map((point, idx) => {
          if (idx === calculateDistance.length - 1) return null;
          const nextPoint = calculateDistance[idx + 1];
          const segment = getNauticalDistance(
            point.lat, point.long, nextPoint.lat, nextPoint.long
          );
          return (
            <li key={`${point.point_id}-${nextPoint.point_id}`}>
              点{point.point_id} → 点{nextPoint.point_id}:{segment} 海里
            </li>
          );
        })}
      </ul>
    </div>
  );
};

export default DistanceCalculator;

注意事项

  • Haversine公式基于地球是完美球体的假设,在大多数航海场景下精度足够;若需更高精度,可替换为Vincenty公式(计算椭圆体表面距离)
  • 确保输入的经纬度是十进制度数(如37.7749,而非度分秒格式)
  • 若坐标数组包含少于2个点,函数会返回0,避免计算错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 10:17:16