Reputation: 69
I know location1.distanceTo(location2)
I need to calculate
distanceX
and
distanceY
from two locations. Is there a way to do it?
CORRECT ANSWER based on njzk2 answer
private Point getDistanceXY(Location location1, Location location2) {
int angle = (int) location1.bearingTo(location2);
Location interm = new Location(location1);
interm.setLongitude(location2.getLongitude());
int distanceX = (int) location1.distanceTo(interm);
int distanceY = (int) location2.distanceTo(interm);
if (angle<=-90) distanceX=-distanceX;
else if (angle>-90 && angle<0) {
distanceX=-distanceX;
distanceY=-distanceY;
}
Log.e("distXY "+name, distanceX+" "+distanceY+" "+angle);
return new Point(distanceX, distanceY);
}
Upvotes: 0
Views: 232
Reputation: 39386
What you could do is create a middle point :
Location interm = new Location(location1);
iterm.setLongitude(location2.getLongitude());
And then,
double distanceX = location1.distance(interm);
double distanceY = interm.distance(location2);
Upvotes: 2
Reputation: 67189
You can use bearingTo() in combination with distanceTo() and a little bit of trigonometry to calculate the X and Y components.
double distY = distance * sin(angle);
double distX = distance * cos(angle);
Upvotes: 1