Search code examples
c#mathcoordinate

Calculate point/coordinate from distance and bearing


Maths is not my strong suit and I think I have something mixed up here but I cannot figure out what.

I'm just trying to populate 2 new coordinates given a number of variables and constants.

if I make Origin coordinate 5,5 and Destination coordinate 10,5, I can work out that distance =5 and that the bearing from Origin to Destination is 90 using these two functions:

private static double GetDistance(PointF point1, PointF point2)
{
        double a = (double)(point2.X - point1.X);
        double b = (double)(point2.Y - point1.Y);

        return Math.Sqrt(a * a + b * b);
    }
public static double GetBearing(PointF coord1, PointF coord2) 
    {
        double result = 0.0;

        result = Math.Atan2(coord2.X - coord1.X, coord2.Y - coord1.Y) * (180 / Math.PI); //- Math.Atan2(coord4.y - coord3.y, coord4.x - coord3.x)) 

        if (result < 0)
        {
            result = result + 360;
        }
        return result;
    }

What I want to be able to do given an offset Distance of xd=1 and an offset bearing of 180(ie directly opposite direction to the destination) is plot the location 4,5. I'd also like to be able to feed a different offset bearing in of say 90 and plot 5,6.

Here's what I've tried but I get completely nonsensical values.

public static PointF CalculateCoordinate(double Angle, double Distance)
    {
        PointF coord = new PointF(Convert.ToSingle(Distance * Math.Cos(Angle)), Convert.ToSingle(Distance * Math.Sin(Angle)));
        return coord;
    }

and CalculateCoordinate(GetBearing(Destination, Origin),1) to reverse the bearing directly 180. I've tried this CalculateCoordinate(90,1) to calculate an offset to the side but that's not working either.

Where have I gone wrong, I'm sure it's something pretty stupid and simple.


Solution

  • There's two mistakes that I can see. First, Atan2 takes the Y value for the first parameter and the X value for the second:

    Math.Atan2(coord2.Y - coord1.Y, coord2.X - coord1.X) * (180 / Math.PI);
    

    Secondly, you're converting from radians to degrees in GetBearing, but you're not converting Angle from degrees to radians inside CalculateCoordinate e.g:

    Math.Cos(Angle * (Math.PI / 180))