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

问题描述:

我正在尝试创建一个方法来计算网格中的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越来越大(更多到中间)。但他们需要更多的在一边,因为经纬度点更远。

直径2公里内的所有纬度/经度点都需要在我的网格中,如果该点距中心0.9公里,则需要接近边线。

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

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

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

如果有人想帮忙,请提前致谢!

我完全重新思考我计算x和y的方法。 我解决它通过执行以下操作:

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

为什么半径是1000? – 2014-09-22 13:42:36

+0

正如我在问题中所说的,直径是2公里。 1km是半径,所以1000m是以米为单位的半径。 – Marc 2014-09-22 13:54:32

+0

你的问题说你想要以像素为单位计算距离,而你详细列出了公里。你试图计算什么?你能否澄清你的问题? – 2014-09-23 12:36:02

不能直接使用距离公式从经度和纬度。你必须考虑球体的曲率来计算距离。

球体上两点之间的最小距离(也就是地球,将其简化为一个完美的球体)是所谓的大圆圈上的弦长度。一个大圆圈是一个以圆心为中心的圆圈)。

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()方法。