Calculating the pixel distance between two locations
I am trying to create a method that calculates the x and y in a grid and ultimately the distance between that point and the environment. The problem is that I only know a few values. To explain the case a little better picture: (values between "(.., ..)" are lat / long combinations).
As you can see, I know the following values:
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)
First, I need to do something to calculate the missing x and y from the points. I've already tried the following:
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);
This works, but I am getting wrong x and y values.
For example, if my lat / long points are further away, x and y get larger (closer to the middle). But they should be more on the side, because the lat / long point is further away.
All lat / long points within a 2 km diameter should be in my grid, if a point is, for example, 0.9 km from the center, it should be almost to the side.
After that I need to calculate the distance between the two points. I already got this part using the following:
Math.sqrt((point.x - point2.x) * (point.x - point2.x) + (point.y - point2.y) * (point.y - point2.y));
My main problem is calculating x and y from my lat / long points.
If anyone wants to help, thanks in advance!
source to share
You cannot directly use the distance from latitude and longitude formula. You will need to consider the curvature of the sphere to calculate the distance.
The minimum distance between two points on a sphere (and therefore the ground, simplifying it to a perfect sphere) is the length of a chord on what is called the Great Circle passing through those points. A great circle is a circle with a center passing through the center of the sphere).
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)
And the distance
(2 * R * arcsin(C/2))
is the radius of the earth or
Another alternative is if you know you will always have Android libraries, this is the method
source to share