计算两个位置之间的像素距离

时间:2014-09-22 13:06:21

标签: java android math location coordinates

我试图创建一种方法来计算网格中的x和y,并最终计算该点与中间点之间的距离。问题是,我只知道几个值。为了更好地解释一下这个案例: enter image description here ('(..,..)'之间的值是纬度/经度组合。

如您所见,我知道以下数值:

start of canvas: xy(0,0)
middle of canvas: xy(540,800) and lat/long(52.3702160, 4.8951680)
max dimension of canvas: x 1080, y 1600
point: xy(?,?) and lat/long(52.4167267, 4.8052174)
point: xy(?,?) and lat/long(52,2422306, 5.1129068)

首先,我需要做一些事情来计算点中缺失的x和y。 我已经尝试过以下操作:

        double mapWidth    = screenWidth;
        double mapHeight   = screenHeight;

// get x value
        x = (location.getLongitude()+180)*(mapWidth/360);

// convert from degrees to radians
        double latRad = location.getLatitude()*Math.PI/180;

// get y value
        double mercN = Math.log(Math.tan((Math.PI/4)+(latRad/2)));
        y     = (mapHeight/2)-(mapWidth*mercN/(2*Math.PI));

        point = new PointF((float)x,(float)y);

这有效,但我得到了错误的x和y值。

例如,如果我的点纬度/经度越远,则x和y越来越大(越往中间)。但他们需要更多的侧面因为纬度/长点更远。

直径2km以内的所有纬度/长点都需要在我的网格中,如果该点距离中心0.9km,则需要几乎在侧面。

之后我需要计算两点之间的距离。我已经使用以下内容获得了该部分:

Math.sqrt((point.x - point2.x) * (point.x - point2.x) + (point.y - point2.y) * (point.y - point2.y));

我的主要问题是从我的纬度/长点计算x和y。

如果有人想要帮助,请提前感谢!

2 个答案:

答案 0 :(得分:0)

我完全重新考虑了计算x和y的方法。 我通过以下方式解决了这个问题:

double distanceMeters = mCurrentLocation.distanceTo(location);
        x = ((1000+distanceMeters)*mMiddleCoords.x)/1000; //1000 = radius.
        y = ((1000+distanceMeters)*mMiddleCoords.y)/1000;

答案 1 :(得分:0)

您无法直接使用纬度和经度的距离公式。您必须考虑球体的曲率来计算距离。

球体上两点之间的最小距离(因此是地球,将其简化为一个完美的球体)是在所谓的通过这些点的大圆圈上的和弦的长度。大圆是一个圆心,其中心穿过球体的中心。)

来自Wikipedia:

C = SQRT(X^2 + Y^2 + Z^2)

其中:

X = cos(lat2) * cos(long2) - cos(lat1) * cos(long1)
Y = cos(lat2) * sin(long2) - cos(lat1) * sin(long1)
Z = sin(lat2) - sin(lat1)

距离为(2 * R * arcsin(C/2)),其中R是地球的半径或6371 km

另一种选择 - 如果你知道你将永远拥有Android库 - 是Location.distanceTo()方法。