Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android - how can I get the bearing degree between two locations?

As title said, I have current location, and want to know the bearing in degree from my current location to other location. I have read this post, is the value return by location.getBearing() my answer?

Let say it simply: from the picture, I expect the value of 45 degree. foo

like image 911
user3143433 Avatar asked Jan 11 '14 09:01

user3143433


1 Answers

I was having trouble doing this and managed to figure it out converting the C? approach to working out the bearing degree.

I worked this out using 4 coordinate points

Start Latitude

Start Longitude

End Latitude

End Longitude

Here's the code:

    protected double bearing(double startLat, double startLng, double endLat, double endLng){
    double latitude1 = Math.toRadians(startLat);
    double latitude2 = Math.toRadians(endLat);
    double longDiff= Math.toRadians(endLng - startLng);
    double y= Math.sin(longDiff)*Math.cos(latitude2);
    double x=Math.cos(latitude1)*Math.sin(latitude2)-Math.sin(latitude1)*Math.cos(latitude2)*Math.cos(longDiff);

    return (Math.toDegrees(Math.atan2(y, x))+360)%360;
}

Just change the variable names were needed.

Output bearing to a TextView

Hope it helped!

like image 60
Bob21 Avatar answered Sep 27 '22 19:09

Bob21