var y = Math.sin(λ2-λ1) * Math.cos(φ2);
var x = Math.cos(φ1)*Math.sin(φ2) -
Math.sin(φ1)*Math.cos(φ2)*Math.cos(λ2-λ1);
var brng = Math.atan2(y, x).toDegrees();
This is my Monkey C implementation:
function getBearing(oldPos, newPos)
{
var lat1 = oldPos.toRadians()[0];
var lat2 = newPos.toRadians()[0];
var lon1 = oldPos.toRadians()[1];
var lon2 = newPos.toRadians()[1];
var y = Math.sin(lon2 - lon1) * Math.cos(lat2);
var x = Math.cos(lat1) * Math.sin(lat2) -
Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1);
return atan2(y,x);
}
I call this with the two positions I want to calculate the direction from like this:
bearing = toDegrees(getBearing(oldPosition, newPosition));
These are my helper functions:
function toDegrees(radian)
{
var degree = radian * 180 / Math.PI;
if(degree < 0)
{
degree = 180 + (180 + degree);
}
return degree;
}
function atan2(y,x)
{
var angle = 0;
if (x == 0)
{
if (y == 0)
{
angle = 0;
}
else if (y > 0)
{
angle = Math.PI/2;
}
else
{
angle = -Math.PI/2;
}
}
else
{
angle = Math.atan(y/x);
if (x < 0)
{
if (y > 0)
{
angle += Math.PI;
}
else if (y < 0)
{
angle -= Math.PI;
}
else
{
angle = Math.PI;
}
}
}
return angle;
}
What I want to see is the direction in degrees from the new Position to the old position. I'm not sure what exactly is wrong here but the result is definately not correct. I'm getting a value in degrees, but it can't be correct. Any help would be appreciated. Thanks in advance.
/Romano