Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative cardinal direction of two coordinates

Tags:

c#

algorithm

Following enum is defined:

public enum Direction
{
    North,
    South,
    East,
    West,
    Northeast,
    Northwest,
    Southeast,
    Southwest,
    Undefined
}

Given two sets of coordinates in two-dimensional space, I'd like to determine the relative cardinal direction from Point 2 to 1.

Examples:

  • P1(1,1) and P2(0,1) returns Direction.North as P2 is north of P1
  • P1(1,1) and P2(5,4) returns Direction.Southeast
  • P1(1,1) and P2(1,1) returns Direction.Undefined

My current approach involves a bunch of conditions, i.e.

if (P1.X == P2.X)
{
    // either North, South or Undefined
    if (P1.Y < P2.Y)
        return Direction.South;
    else if (P1.Y > P2.Y)
        return Direction.North,
    else
        return Direction.Undefined;
}
else if (P1.Y == P2.Y)
{
    ...
}
else 
{
    ...
}

I'm seeking a shorter and more elegant solution.

like image 880
JCarter Avatar asked Jan 30 '16 17:01

JCarter


People also ask

What are the 2 cardinal directions?

North, east, south, and west are the four cardinal directions, often marked by the initials N, E, S, and W. East and west are at right angles to north and south. East is in the clockwise direction of rotation from north. West is directly opposite east.

What is relative and cardinal directions?

The four cardinal directions, or cardinal points, are the four main compass directions: north, east, south, and west, commonly denoted by their initials N, E, S, and W respectively. Relative to north, the directions east, south, and west are at 90 degree intervals in the clockwise direction.

What are the 8 cardinal points?

A compass rose with both ordinal and cardinal directions will have eight points: N, NE, E, SE, S, SW, W, and NW.

What determines cardinal direction?

Cardinal directions are one set of directions that people around the world use. The four cardinal directions are north, south, east and west. These directions use the rising and setting of the sun as reference points. Because the Earth rotates from west to east, the sun appears to rise in the east and set in the west.


1 Answers

My 3 cents - i'm waiting for improvements

Here is the enum:

public enum Direction
{
    North = 0,
    South = 4,
    East = 6,
    West = 2,
    Northeast = 7,
    Northwest = 1,
    Southeast = 5,
    Southwest = 3,
    Undefined = -1
}

and the conversion goes as:

public static Direction GetDirection(Point p1, Point p2) {
    double angle = Math.Atan2(p2.Y - p1.Y, p2.X - p1.X);
    angle += Math.PI;
    angle /= Math.PI / 4;
    int halfQuarter = Convert.ToInt32(angle);
    halfQuarter %= 8;
    return (Direction)halfQuarter;
}

It does not return Direction.Undefined however, because

if y is 0 and x is 0, θ = 0.

(from https://msdn.microsoft.com/library/system.math.atan2(v=vs.110).aspx)

like image 128
romanoza Avatar answered Oct 06 '22 00:10

romanoza