Search code examples
c#geography

Determine if point is in a rectangle using map coordiates


My brain just isn't working today. I need to test whether a point (lat, long) lies within a a rectangle on a map. The rectangle is defined by it's North, East, South, & West borders. The hiccup is that all points or values are in map-coordinate system. To deal with the date-line wrap-around, I assume that longitude is always "between" if we go from left-to-right.

bool PointInRectangle(Point pt, double North, double East, double South, double West)
{
    // ????
}

Solution

  • Assuming east and north are positive:

    bool PointInRectangle(Point pt, double North, double East, double South, double West)
    {
        // you may want to check that the point is a valid coordinate
        if (West < East)
        {
            return pt.X < East && pt.X > West && pt.Y < North && pt.Y > South;
        }
    
        // it crosses the date line
        return (pt.X < East || pt.X > West) && pt.Y < North && pt.Y > South;        
    }