How to convert radians to degrees - java

I'm making a trig calculator to practice aviation problems for fun and can't convert radians to degrees properly in java.
I've tried taking altitude divided by Math.tan(angle) and times it by (180 / Math.PI) but this doesn't give me the answer I'm looking for.
The numbers I've tried include alt = 500, angle of approach = 3. My code will store these values and take 500/tan(3) * (180/Pi) and I'm unsure why this isn't the correct trigonometry behind it.
public static void approachPath() {
System.out.println("FINDING THE IDEAL APPROACH PATH . . . ");
System.out.println("What is the altitude of the aircraft:");
double alt = scan.nextDouble();
System.out.println("What is the angle of approach:");
double angleofapproach = scan.nextDouble();
//line my problem occurs on
double approachPath = (alt / Math.tan(angleofapproach)) * (180 / Math.PI);
System.out.println("The ideal approach path is: " + approachPath);
}
I'm expecting the answer 9,541feet so I can move on to writing the rest of the method to find the final approach path in nautical miles.

You were almost right. Just instead of rad to deg, it should be deg to rad.
double angleofapproach = toRad(scan.nextDouble());
double approachPath = (alt / Math.tan(angleofapproach));
// deg to rad
public static double toRad(double deg) {
return deg * (Math.PI / 180);
}

Related

Calculating degrees to radians in terms of pi

I made a code converting degrees to radians following my teacher's format but I want to try to make it in terms of pi. Right now when I plug in 30 as my degrees the output is a loooong decimal but I want it to come out as pi/6. Is there a way to keep the pi symbol in the output?
This is my current code:
public static double convertDeg(double deg)
{
double rad = deg * (Math.PI/180);
return rad;
}
and
System.out.println("Degrees to radians: "+Calculate.convertDeg(30));
The output is: "Degrees to radians: 0.5235987755982988"
"but I want it to come out as pi/6."
To get this format; Try this.
public static String convertDeg(double deg)
{
String rad = "Math.PI/"+(180/deg);
return rad;
}
It returns a string as the method return type is string.
It does'nt exactly return "pi/6" but "Math.PI/6".
So get the idea for its use from this;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
class HelloWorld {
public static String convertDeg(double deg)
{
String rad = "Math.PI/"+(180/deg);
return rad;
}
public static void main(String[] args) {
ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js");
try {
Object result = engine.eval(convertDeg(30));
System.out.println("\nDegree to Radian = "+result);
}
catch (ScriptException e) {
// Something went wrong
e.printStackTrace();
}
}
}
Its answer is as follows,
Degree to Radian = 0.5235987755982988
You can't set formatting up to convert degrees to radians with pi out of the box in java, but you can write your own function to do this.
We know that
360 degrees = 2 * PI radians =>
180 degrees = PI radians =>
1 degree = PI / 180 radians =>
Therefore
X degrees = PI * (X / 180) radians
In case degrees is an integer value
we can simplify a fraction X / 180
if gcd(X, 180) > 1, gcd -- the greater common divider.
X / 180 = (X / gcd(X, 180)) / (180 / gcd(X, 180))
The code is something like this (don't forget to check corner cases):
String formatDegreesAsFractionWithPI(int degrees) {
int gcd = gcd(degrees, 180);
return "(" + (degrees / gcd) + " / " + (180 / gcd) + ") * PI"
}
int gcd(int a, int b) = { ... }
In case degrees is a floating point number,
the problem is more complicated and my advice
is to read about 'converting decimal floating
point number to integers fraction'.
Related questions: gcd in java, convert float to fraction (maybe works)

Increase Latitude and longitude by given Distance (meter) Using JAVA [duplicate]

I want to create 2 new longitude and 2 new latitudes based on a coordinate and a distance in meters, I want to create a nice bounding box around a certain point. It is for a part of a city and max ±1500 meters. I therefore don't think the curvature of earth has to be taken into account.
So I have 50.0452345 (x) and 4.3242234 (y) and I want to know x + 500 meters, x - 500 meters, y - 500 meters, y + 500 meters
I found many algorithms but almost all seem to deal with the distance between points.
The number of kilometers per degree of longitude is approximately
(pi/180) * r_earth * cos(theta*pi/180)
where theta is the latitude in degrees and r_earth is approximately 6378 km.
The number of kilometers per degree of latitude is approximately the same at all locations, approx
(pi/180) * r_earth = 111 km / degree
So you can do:
new_latitude = latitude + (dy / r_earth) * (180 / pi);
new_longitude = longitude + (dx / r_earth) * (180 / pi) / cos(latitude * pi/180);
As long as dx and dy are small compared to the radius of the earth and you don't get too close to the poles.
The accepted answer is perfectly right and works. I made some tweaks and turned into this:
double meters = 50;
// number of km per degree = ~111km (111.32 in google maps, but range varies
// between 110.567km at the equator and 111.699km at the poles)
//
// 111.32km = 111320.0m (".0" is used to make sure the result of division is
// double even if the "meters" variable can't be explicitly declared as double)
double coef = meters / 111320.0;
double new_lat = my_lat + coef;
// pi / 180 ~= 0.01745
double new_long = my_long + coef / Math.cos(my_lat * 0.01745);
Hope this helps too.
For latitude do:
var earth = 6378.137, //radius of the earth in kilometer
pi = Math.PI,
m = (1 / ((2 * pi / 360) * earth)) / 1000; //1 meter in degree
var new_latitude = latitude + (your_meters * m);
For longitude do:
var earth = 6378.137, //radius of the earth in kilometer
pi = Math.PI,
cos = Math.cos,
m = (1 / ((2 * pi / 360) * earth)) / 1000; //1 meter in degree
var new_longitude = longitude + (your_meters * m) / cos(latitude * (pi / 180));
The variable your_meters can contain a positive or a negative value.
I had to spend about two hours to work out the solution by #nibot , I simply needed a method to create a boundary box given its center point and width/height (or radius) in kilometers:
I don't fully understand the solution mathematically/ geographically.
I tweaked the solution (by trial and error) to get the four coordinates. Distances in km, given the current position and distance we shift to the new position in the four coordinates:
North:
private static Position ToNorthPosition(Position center, double northDistance)
{
double r_earth = 6378;
var pi = Math.PI;
var new_latitude = center.Lat + (northDistance / r_earth) * (180 / pi);
return new Position(new_latitude, center.Long);
}
East:
private static Position ToEastPosition(Position center, double eastDistance)
{
double r_earth = 6378;
var pi = Math.PI;
var new_longitude = center.Long + (eastDistance / r_earth) * (180 / pi) / Math.Cos(center.Lat * pi / 180);
return new Position(center.Lat, new_longitude);
}
South:
private static Position ToSouthPosition(Position center, double southDistance)
{
double r_earth = 6378;
var pi = Math.PI;
var new_latitude = center.Lat - (southDistance / r_earth) * (180 / pi);
return new Position(new_latitude, center.Long);
}
West:
private static Position ToWestPosition(Position center, double westDistance)
{
double r_earth = 6378;
var pi = Math.PI;
var new_longitude = center.Long - (westDistance / r_earth) * (180 / pi) / Math.Cos(center.Lat * pi / 180);
return new Position(center.Lat, new_longitude);
}
Have you checked out: How do I find the lat/long that is x km north of a given lat/long ?
These calculations are annoying at best, I've done many of them. The haversine formula will be your friend.
Some reference: http://www.movable-type.co.uk/scripts/latlong.html
Posting this method for sake of completeness.
Use this method "as it is" to:
Move any (lat,long) point by given meters in either axis.
Python method to move any point by defined meters.
def translate_latlong(lat,long,lat_translation_meters,long_translation_meters):
''' method to move any lat,long point by provided meters in lat and long direction.
params :
lat,long: lattitude and longitude in degrees as decimal values, e.g. 37.43609517497065, -122.17226450150885
lat_translation_meters: movement of point in meters in lattitude direction.
positive value: up move, negative value: down move
long_translation_meters: movement of point in meters in longitude direction.
positive value: left move, negative value: right move
'''
earth_radius = 6378.137
#Calculate top, which is lat_translation_meters above
m_lat = (1 / ((2 * math.pi / 360) * earth_radius)) / 1000;
lat_new = lat + (lat_translation_meters * m_lat)
#Calculate right, which is long_translation_meters right
m_long = (1 / ((2 * math.pi / 360) * earth_radius)) / 1000; # 1 meter in degree
long_new = long + (long_translation_meters * m_long) / math.cos(lat * (math.pi / 180));
return lat_new,long_new
Working Python code to offset coordinates by 10 metres.
def add_blur(lat, long):
meters = 10
blur_factor = meters * 0.000006279
new_lat = lat + blur_factor
new_long = long + blur_factor / math.cos(lat * 0.018)
return new_lat, new_long
if you don't have to be very exact then: each 10000 meters is about 0.1 for latitude and longitude.
for example I want to load locations 3000 meters around point_A from my database:
double newMeter = 3000 * 0.1 / 10000;
double lat1 = point_A.latitude - newMeter;
double lat2 = point_A.latitude + newMeter;
double lon1 = point_A.longitude - newMeter;
double lon1 = point_A.longitude + newMeter;
Cursor c = mDb.rawQuery("select * from TABLE1 where lat >= " + lat1 + " and lat <= " + lat2 + " and lon >= " + lon1 + " and lon <= " + lon2 + " order by id", null);
public double MeterToDegree(double meters, double latitude)
{
return meters / (111.32 * 1000 * Math.Cos(latitude * (Math.PI / 180)));
}
var meters = 50;
var coef = meters * 0.0000089;
var new_lat = map.getCenter().lat.apply() + coef;
var new_long = map.getCenter().lng.apply() + coef / Math.cos(new_lat * 0.018);
map.setCenter({lat:new_lat, lng:new_long});
See from Official Google Maps Documentation (link below) as they solve on easy/simple maps the problems with distance by countries :)
I recommended this solution to easy/simply solve issue with boundaries that you can know which area you're solving the problem with boundaries (not recommended globally)
Note:
Latitude lines run west-east and mark the position south-north of a point. Lines of latitude are called parallels and in total there are 180 degrees of latitude. The distance between each degree of latitude is about 69 miles (110 kilometers).
The distance between longitudes narrows the further away from the equator. The distance between longitudes at the equator is the same as latitude, roughly 69 miles (110 kilometers) . At 45 degrees north or south, the distance between is about 49 miles (79 kilometers). The distance between longitudes reaches zero at the poles as the lines of meridian converge at that point.
Original source 1
Original source 2
Official Google Maps Documentation: Code Example: Autocomplete Restricted to Multiple Countries
See the part of their code how they solve problem with distance center + 10 kilometers by +/- 0.1 degree
function initMap(): void {
const map = new google.maps.Map(
document.getElementById("map") as HTMLElement,
{
center: { lat: 50.064192, lng: -130.605469 },
zoom: 3,
}
);
const card = document.getElementById("pac-card") as HTMLElement;
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(card);
const center = { lat: 50.064192, lng: -130.605469 };
// Create a bounding box with sides ~10km away from the center point
const defaultBounds = {
north: center.lat + 0.1,
south: center.lat - 0.1,
east: center.lng + 0.1,
west: center.lng - 0.1,
};
const input = document.getElementById("pac-input") as HTMLInputElement;
const options = {
bounds: defaultBounds,
componentRestrictions: { country: "us" },
fields: ["address_components", "geometry", "icon", "name"],
origin: center,
strictBounds: false,
types: ["establishment"],
};
This is what I did in VBA that seems to be working for me. Calculation is in feet not meters though
Public Function CalcLong(OrigLong As Double, OrigLat As Double, DirLong As String, DirLat As String, DistLong As Double, DistLat As Double)
Dim FT As Double
Dim NewLong, NewLat As Double
FT = 1 / ((2 * WorksheetFunction.Pi / 360) * 20902230.971129)
If DirLong = "W" Then
NewLat = CalcLat(OrigLong, OrigLat, DirLong, DirLat, DistLong, DistLat)
NewLong = OrigLong - ((FT * DistLong) / Cos(NewLat * (WorksheetFunction.Pi / 180)))
CalcLong = NewLong
Else
NewLong = OrigLong + ((FT * DistLong) / Math.Cos(CalcLat(OrigLong, OrigLat, DirLong, DirLat, DistLong, DistLat) * (WorksheetFunction.Pi / 180)))
CalcLong = NewLong
End If
End Function
Public Function CalcLat(OrigLong As Double, OrigLat As Double, DirLong As String, DirLat As String, DistLong As Double, DistLat As Double) As Double
Dim FT As Double
Dim NewLat As Double
FT = 1 / ((2 * WorksheetFunction.Pi / 360) * 20902230.971129)
If DirLat = "S" Then
NewLat = (OrigLat - (FT * DistLat))
CalcLat = NewLat
Else
NewLat = (OrigLat + (FT * DistLat))
CalcLat = NewLat
End If
End Function
Original poster said:
"So I have 50.0452345 (x) and 4.3242234 (y) and I want to know x + 500 meters..."
I will assume the units of the x and y values he gave there were in meters (and not degrees Longitude, Latitude). If so then he is stating measurements to 0.1 micrometer, so I will assume he needs similar accuracy for the translated output. I also will assume by "+500 meters" etc. he meant
the direction to be due North-South and due East-West.
He refers to a reference point:
"2 new latitudes based on a coordinate";
but he did not give the Longitude and Latitude,
so to explain the procedure concretely I will give
the Latitudes and Longitudes for the corners of the
500 meter box he requested around the point
[30 degrees Longitude,30 degrees Latitude].
The exact solution on the surface of the GRS80 Ellipsoid is
given with the following set of functions
(I wrote these for the free-open-source-mac-pc math program called "PARI"
which allows any number of digits precision to be setup):
\\=======Arc lengths along Latitude and Longitude and the respective scales:
dms(u)=[truncate(u),truncate((u-truncate(u))*60),((u-truncate(u))*60-truncate((u-truncate(u))*60))*60];
SpinEarthRadiansPerSec=7.292115e-5;\
GMearth=3986005e8;\
J2earth=108263e-8;\
re=6378137;\
ecc=solve(ecc=.0001,.9999,eccp=ecc/sqrt(1-ecc^2);qecc=(1+3/eccp^2)*atan(eccp)-3/eccp;ecc^2-(3*J2earth+4/15*SpinEarthRadiansPerSec^2*re^3/GMearth*ecc^3/qecc));\
e2=ecc^2;\
b2=1-e2;\
b=sqrt(b2);\
fl=1-b;\
rfl=1/fl;\
U0=GMearth/ecc/re*atan(eccp)+1/3*SpinEarthRadiansPerSec^2*re^2;\
HeightAboveEllipsoid=0;\
reh=re+HeightAboveEllipsoid;\
longscale(lat)=reh*Pi/648000/sqrt(1+b2*(tan(lat))^2);
latscale(lat)=reh*b*Pi/648000/(1-e2*(sin(lat))^2)^(3/2);
longarc(lat,long1,long2)=longscale(lat)*648000/Pi*(long2-long1);
latarc(lat1,lat2)=(intnum(th=lat1,lat2,sqrt(1-e2*(sin(th))^2))+e2/2*sin(2*lat1)/sqrt(1-e2*(sin(lat1))^2)-e2/2*sin(2*lat2)/sqrt(1-e2*(sin(lat2))^2))*reh;
\\=======
I then plugged the reference point [30,30]
into those functions at the PARI command prompt
and had PARI solve for the point +/- 500 meters away
from it, giving the two new Longitudes and
two new Latitudes that the original poster asked for.
Here is the input and output showing that:
? dms(solve(x=29,31,longarc(30*Pi/180,30*Pi/180,x*Pi/180)+500))
cpu time = 1 ms, real time = 1 ms.
%1172 = [29, 59, 41.3444979398934670450280297216509190843055]
? dms(solve(x=29,31,longarc(30*Pi/180,30*Pi/180,x*Pi/180)-500))
cpu time = 1 ms, real time = 1 ms.
%1173 = [30, 0, 18.6555020601065329549719702783490809156945]
? dms(solve(x=29,31,latarc(30*Pi/180,x*Pi/180)+500))
cpu time = 1,357 ms, real time = 1,358 ms.
%1174 = [29, 59, 43.7621925447500548285775757329518579545513]
? dms(solve(x=29,31,latarc(30*Pi/180,x*Pi/180)-500))
cpu time = 1,365 ms, real time = 1,368 ms.
%1175 = [30, 0, 16.2377963202802863245716034907838199823349]
?

How to go about using tangents in Java?

I was bored and wanted to practice my java coding skills. I made a program that finds the area of a polygon based on what you know (radius, perimeter, apothem).
Here's a portion:
static void pentagon() {
System.out.println("Select what you know");
System.out.println("[1]Perimeter\n[2]Apothem\n[3]Radius");
info = input.nextInt();
if (info == 1) {
System.out.println("What is the perimeter of the pentagon?");
double per = input.nextDouble();
double apothem = per * .137638192;
double answer = apothem * per * .5;
System.out.println("The area of the pentagon is " + answer + " square units.");
} else if (info == 2) {
System.out.println("What is the apothem of the pentagon?");
double apothem = input.nextDouble();
double per = apothem / .137638192;
double answer = apothem * per * .5;
System.out.println("The area of the pentagon is " + answer + " square units.");
} else if (info == 3) {
System.out.println("What is the radius of the pentagon?");
double rad = input.nextDouble();
double per = rad / .1701301617;
double apothem = per * .137638192;
double answer = apothem * per * .5;
System.out.println("The area of the pentagon is " + answer + " square units.");
}
}
Due to the problem that all those decimals (ratio of apothem to perimeter) I had to figure out myself, I could only code a few useful ones.
If I knew how to use tangents, I could figure this out.
Ex: double apothem = length / tan(360/10/2)
(An apothem of a decagon)
Can someone show me how to code the previous line?
The recomended way would be to use java.lang.Math.tan(double a)
double apothem = 1 / java.lang.Math.tan( (2*java.lang.Math.PI)/(10*2))
unless there is some reason why you need extraordinary precision and this does not provide it. Then you may be able to find some third party alternative.
You're looking for the java.lang.Math class which has all the trig functions along with other useful constants like e and PI
So the apothem of a decagon where each side was length long and the equation = length/ 2 tan(180/ n) would be (after importing the Math class by putting at the top of your java file import java.lang.Math; )
EDIT
As user ajb points out, Math.tan() takes radians so you have to convert degrees to radians so you have to use toRadians() to convert from degrees to radians:
double apothem = length / (2 *Math.tan(Math.toRadians(180/10))

How do I write a Java program that calculates the distance between two points on earth?

I know how to start it out and I know how to put in the scanners and everything, but in school, I've never really learned about longitude and latitude formulas and how to convert those points into radians. So I'm pretty much stuck on this Java problem. Here is what I have so far:
import java.util.*;
class DistanceCalculator {
// Radius of the earth in km; this is the class constant.
public static final double Radius = 6372.795;
/**
* This program computes the spherical distance between two points on the surface of the Earth.
*/
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
intro();
System.out.print("Longitude (degrees.minutes) ");
double Longitude = console.nextDouble();
System.out.print("Latitude (degrees.minutes) ");
double Latitude = console.nextDouble();
}
public static double distFrom(double lat1, double lng1, double lat2, double lng2);
double Latitude = Math.toRadians(...);
}
public static void intro() {
System.out.println("This program computes the spherical distance between two points on the surface of the Earth.");
System.out.println("\tPlease start by entering the longitude and the latitude of location 1.");
}
}
In Java IDE, they say that Longitude and Latitude points (the ones underneath the intro();) are not used, and I know why, since I haven't really defined them yet.
I know I'm missing the formula for longitude and latitude. In my book, it wants me to use the spherical law of cosines, and since I've never learned this at school, no matter how hard I study the formula from the websites I sought out, I don't know how to transfer that into Java language.
Another problem is, how do I transfer degrees and minutes from a longitude/latitude point into radians? Do I have to use Math.toRadians thing? Oh yeah and also, my answer has to be in kilometers.
Updated: The math functions some of you guys are talking about confuses me greatly. In school (I'm a high schooler), even at Math IB SL, my teacher has never taught us how to find long/lat. points...yet. So it's hard for me to grasp. Since the spherical law of cosines formula is online, do I basically just take that formula and convert it into "java language" and plug it into my program?
The key word you need to search for is the "Haversine formula".
An easier to understand method, but one which is not quite so accurate for small distances, is to recall that the angle between two vectors A and B can be calculated using the dot product:
A ⋅ B = |A| * |B| * cos(theta)
so if you convert your polar lat/long pairs into 3D cartesian coordinates (and yes, you'll need to use Math.toRadians(), Math.cos() and Math.sin() to do that, and then calculate the dot product, you'll then get cos(theta), so use Math.acos() to get theta.
You can then work out the distance simply as D = R * theta, where R is the radius of the Earth, and theta remains in radians.
I suggest to read more about WGS84.
Mathematical explanations here.
You may look at this link for the logic.
http://aravindtrue.wordpress.com/2009/06/30/calculate-distance-using-latitude-and-longitude-php-mysql/
Function in PHP... I don't know Java. So some one edit my post. Here is the PHP function:
function getDistanceBetweenPointsNew($latitude1, $longitude1,
$latitude2, $longitude2, $unit = 'Mi')
{
$theta = $longitude1 - $longitude2;
$distance = (sin(deg2rad($latitude1)) *
sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) *
cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
$distance = acos($distance);
$distance = rad2deg($distance);
$distance = $distance * 60 * 1.1515;
switch($unit)
{
case 'Mi': break;
case 'Km' : $distance = $distance *1.609344;
}
return (round($distance,2));
}
also to get value from MySQL database:
Calculate distance given 2 points, latitude and longitude
I tried to create a java function, I don't know if it work or not.
try this. If any one can help, try edit my java code.
import java.math.BigDecimal;
public static double round(double unrounded, int precision, int roundingMode)
{
BigDecimal bd = new BigDecimal(unrounded);
BigDecimal rounded = bd.setScale(precision, roundingMode);
return rounded.doubleValue();
}
public static double distFrom(double lat1, double lng1, double lat2, double lng2, String unit)
{
double theta = lng1 - lng2;
double distance = (
Math.sin(Math.toRadians(lat1)) * Math.sin(Math.toRadians(lat2))
)+(
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.cos(Math.toRadians(theta))
);
distance = Math.acos(distance);
distance = Math.toDeg(distance);
distance = distance * 60 * 1.1515;
switch(unit)
{
/* Mi = miles, Km = Kilometers */
case "Mi" :
break;
case "Km" :
distance = distance *1.609344;
break;
}
distance = round(distance, 2, BigDecimal.ROUND_HALF_UP);
return distance;
}
import java.util.*;
public class SphericalDistance {
public static void main(String[] args){
System.out.println(" This program computes the spherical distance\n between two points, 1 and 2.");
System.out.println(" Please enter the latitude and longitude for \n each point as a pair of integers, degrees \n followed by minutes:");
System.out.print("Latitude 1:");
Scanner s=new Scanner(System.in);
double latangledeg = s.nextDouble();
double latanglemin = s.nextDouble()/60;
double phideg = latangledeg + latanglemin;
double phi1 = phideg * Math.PI/180;
System.out.print("Longitude 1:");
double lonangledeg = s.nextDouble();
double lonanglemin = s.nextDouble()/60;
double lambdadeg = lonangledeg + lonanglemin;
double lambda1 = lambdadeg * Math.PI/180;
System.out.println("Latitude 2:");
double latangledeg2 = s.nextDouble();
double latanglemin2 = s.nextDouble()/60;
double phideg2 = latangledeg2 + latanglemin2;
double phi2 = phideg2 * Math.PI/180;
System.out.println("Longitude 2:");
double lonangledeg2 = s.nextDouble();
double lonanglemin2 = s.nextDouble()/60;
double lambdadeg2 = lonangledeg2 + lonanglemin2;
double lambda2 = lambdadeg2 * Math.PI/180;
double lambdaf = lambda2 - lambda1;
double angdistance = Math.acos(Math.sin(phi1)*Math.sin(phi2) + Math.cos(phi1)*Math.cos(phi2)*Math.cos(lambdaf));
System.out.println("Angular Distance = " + angdistance + " radians");
int distancekm = (int)(angdistance * 6372.795);
int distancemi = (int) (distancekm * .621371);
System.out.println("Distance = " + distancekm + " kilometers");
System.out.println("Distance = " + distancemi + " miles");
s.close();
}
}

Java - Trigonometry Hell

I have a task of being able to program a Class in Java to calculate the bearing from North to a point. The only objects that are known are 2 positions, both have a bearing from North and the distance from 0. So for example - position 1 - 30 degrees and 10m, position 2 - 190 degrees and 50m. How would you calculate the bearing if you wanted to travel from position 1 to position 2 for instance or from position 2 to 1? I can calculate the distance between the 2 positions using the cosine rule, but have no idea how to create a class that will accuratly calculate the bearing in different scenarios?
Any help or advise would be greatly appreciated.
From http://en.wikipedia.org/wiki/Law_of_cosines#Applications:
...once you have all three side lengths, this will give you the third angle of your triangle.
(The Haversine formula is for navigation on a sphere... I think we're just worried about vectors on a plane.)
I believe what you are looking for is the Haversine formula, googling it will yield implementations in various languages.
This is a java version ported from a javascript solution given here:
Using the Haversine Formula in Javascript by talkol
// this was a pojo class we used internally...
public class GisPostalCode {
private String country;
private String postalCode;
private double latitude;
private double longitude;
// getters/setters, etc.
}
public static double distanceBetweenCoordinatesInMiles2(GisPostalCode c1, GisPostalCode c2) {
double lat2 = c2.getLatitude();
double lon2 = c2.getLongitude();
double lat1 = c1.getLatitude();
double lon1 = c1.getLongitude();
double R = 6371; // km
double x1 = lat2 - lat1;
double dLat = x1 * Math.PI / 180;
double x2 = lon2 - lon1;
double dLon = x2 * Math.PI / 180;
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1*Math.PI/180) * Math.cos(lat2*Math.PI/180) *
Math.sin(dLon/2) * Math.sin(dLon/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double d = R * c;
// convert to miles
return d / 1.60934;
}

Categories