Search code examples
latitude-longitudecomputational-geometrypoint-in-polygon

Given a list of GPS coordinates making up a boundary, how can I calculate if my location is within that boundary?


Suppose I have hundreds, or even thousands of GPS coords, Latitude and Longitude that make up a boundary around a country.

I also have my current position Latitude and Longitude.

How can I determine (using C#, programming for Windows10 UWP) if my position is within the boundary of a country?

E.G. Suppose I have all the points that make up red line in the image below. If I was at the X location, my function would return true. If I were at the Y location, my function would return false.

MapExample


Solution

  • Thanks to the two answers received I found out the actual name of what I was trying to do... "Point in Polygon".

    Knowing this, I was able to find this Stack Overflow question and answer

    Here's the code should the above ever disappear:

    /// <summary>
    /// Determines if the given point is inside the polygon
    /// </summary>
    /// <param name="polygon">the vertices of polygon</param>
    /// <param name="testPoint">the given point</param>
    /// <returns>true if the point is inside the polygon; otherwise, false</returns>
    public static bool IsPointInPolygon4(PointF[] polygon, PointF testPoint)
    {
        bool result = false;
        int j = polygon.Count() - 1;
        for (int i = 0; i < polygon.Count(); i++)
        {
            if (polygon[i].Y < testPoint.Y && polygon[j].Y >= testPoint.Y || polygon[j].Y < testPoint.Y && polygon[i].Y >= testPoint.Y)
            {
                if (polygon[i].X + (testPoint.Y - polygon[i].Y) / (polygon[j].Y - polygon[i].Y) * (polygon[j].X - polygon[i].X) < testPoint.X)
                {
                    result = !result;
                }
            }
            j = i;
        }
        return result;
    }
    

    It takes an array of points that make up the polygon and a point to test and returns true or false. Works well in all my testing.