我怎么知道两个坐标之间的距离?

时间:2020-03-11 18:01:16

标签: java coordinates

也许这不是我要寻找答案的网站,但这是我的问题。

我正在开发Java程序,因此我需要知道两个位置之间的距离(以米为单位),因为其坐标格式为EPSG:4326。

例如,

坐标1:

42.34839, 2.484839

坐标2:

42.27345, 2.23453

从数学上讲,知道两个坐标之间的距离差的系统是什么?

1 个答案:

答案 0 :(得分:0)

有很多不同的算法来确定两个点之间的距离。例如,曼哈顿距离是非常简单的IIRC,只有abs(x1-x2)+ abs(y1-y2)。

class Coordinate {

    private final float x;

    private final float y;

    Coordinate(float x, float y) {
        this.x = x;
        this.y = y;
    }

    public float manhattanDistance(Coordinate other) {
        return Math.abs(x - other.x) + Math.abs(y - other.y);
    }

    public float getX() {
        return x;
    }

    public float getY() {
        return y;
    }
}
Coordinate first = new Coordinate(42.34839f, 2.484839f);

Coordinate second = new Coordinate(42.27345f, 2.23453f);

float manhattanDistance = first.manhattanDistance(second);

System.out.println("distance: " + manhattanDistance);

输出

distance: 0.32524872