user2007094
user2007094

Reputation: 69

Android get distance X and Y beetween Locations

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

Answers (2)

njzk2
njzk2

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

Bryan Herbst
Bryan Herbst

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

Related Questions