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

Java中Location类大圆距离计算实现的技术咨询

大圆距离公式实现困惑:Location类calcDistance方法解析

问题背景

我把原本同一个类里的Station和Location拆分后,大部分代码已经完成,但在通过距离计算关联两个类时卡壳了。尤其搞不懂Location类里calcDistance方法的实现逻辑,不清楚大圆距离公式里lat2、lon2到底对应哪个对象的坐标,希望搞明白这些后自己完成Station类的开发。

现有Location类代码

// Models a location
public class Location {
    // instant variables
    private double latitude;
    private double longitude;
    
    // constant (Approximate radius of earth in miles.
    public static final double EARTH_RADIUS = 3959.0;

    // Constructor for objects of class Location
    public Location(double inLatitude, double inLongitude) {
        this.latitude = inLatitude;
        this.longitude = inLongitude;
    }

    // returns latitude of the Location
    public double getLatitude() {
        return this.latitude;
    }

    // returns longitude of the Location
    public double getLongitude() {
        return this.longitude;
    }

    /**
     * Calculates approximate distance between this location
     * and the parameter value location.
     * 
     * @param  inLocation Location  input Location.
     * @return double  distance in miles
     */
    public double calcDistance(Location inLocation) {
        // 这里是我搞不懂的部分,需要实现逻辑
    }
}

注:修正了原代码里的语法错误,比如构造函数里的this.Longitude拼写错误、getLongitude方法里的多余括号

实验指导要求

  • 第一步:用Math.toRadians()方法把经纬度(度数)转换成弧度
  • 第二步:使用大圆距离公式计算:

    3959.0 * ArcCos[ sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(lon2 - lon1) ]
    其中Math.acos()对应ArcCos,Math.cos()对应余弦,Math.sin()对应正弦,3959.0是地球近似半径(英里)

核心逻辑解析

先明确公式里的参数对应关系:

  • lat1、lon1:当前调用calcDistance方法的Location对象(也就是this)的经纬度,需要转成弧度
  • lat2、lon2:方法参数inLocation对应的另一个Location对象的经纬度,同样需要转成弧度

calcDistance方法完整实现

public double calcDistance(Location inLocation) {
    // 1. 把当前对象的经纬度转成弧度
    double lat1 = Math.toRadians(this.getLatitude());
    double lon1 = Math.toRadians(this.getLongitude());
    
    // 2. 把传入的Location对象的经纬度转成弧度
    double lat2 = Math.toRadians(inLocation.getLatitude());
    double lon2 = Math.toRadians(inLocation.getLongitude());
    
    // 3. 代入大圆距离公式计算
    double distance = EARTH_RADIUS * Math.acos(
        Math.sin(lat1) * Math.sin(lat2) + 
        Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1)
    );
    
    return distance;
}

代码逻辑说明

  1. 弧度转换:Java的Math类三角函数方法默认用弧度计算,必须先把度数转成弧度,否则结果会完全错误
  2. 公式代入:严格按照实验指导的公式,用Math.acos计算反余弦,再乘以地球半径得到英里数的距离
  3. 变量复用:直接用类里定义的EARTH_RADIUS常量,避免硬编码数值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 04:44:56