Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to calculate bearing

807589Jun 19 2008 — edited Jun 23 2008
I have two points and I need to calculate the direction one would have to go to reach the other point, the so called bearing.

I have found a formula and it seems to be sensible, but I am never getting what seems to be the correct results.

For example for Arth-Goldau in Switzerland I have coordinates 684,408 x 211,500 and for Luzern I have 666,223 x 211,383. Just by looking at the coordinates you can see that the bearing would likely be mostly easterly. What I am getting back for a bearing of 43 degrees or NE. For several other points I am getting weird results that do not match any pattern I can see. For example for Bern 600,037 x 199,749 I am getting a bearing of 10 degrees.

Does anyone have any clues? Thanks.
	public static double calcBearing(double lat1, double lon1, double lat2, double lon2) {
		
		// to convert degrees to radians, multiply by:
		final double rad = Math.toRadians(1.0);
		// to convert radians to degrees:
		final double deg = Math.toDegrees(1.0);
		
		double GLAT1 = rad * (lat1);
		double GLAT2 = rad * (lat2);
		double GLON1 = rad * (lon1);
		double GLON2 = rad * (lon2);
		
		// great circle angular separation in radians
		double alpha = Math.acos(Math.sin(GLAT1) * Math.sin(GLAT2) + Math.cos(GLAT1) * Math.cos(GLAT2)
				* Math.cos(GLON1 - GLON2));
		
		// forward azimuth from point 1 to 2 in radians
		double s2 = rad * (90.0 - lat2);
		double FAZ = Math.asin(Math.sin(s2) * Math.sin(GLON2 - GLON1) / Math.sin(alpha));
		
		double result = FAZ * deg; // radians to degrees
		if (result < 0.0) result += 360.0; // reset az from -180 to 180 to 0 to 360
			
		return result;
	}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 21 2008
Added on Jun 19 2008
18 comments
1,009 views