2

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

Jan
  • 2,060
  • 2
  • 29
  • 34
Percy
  • 2,855
  • 2
  • 33
  • 56
  • Use some spatial data api http://stackoverflow.com/questions/2184469/know-of-any-c-sharp-spatial-data-libraries – gabba Feb 17 '16 at 15:46

3 Answers3

5

Define a point that is surely on the outside, or is surely on the inside.

Now create a line from your position to that known point, and intersect it with each segment of the circumference. Count the numbers of intersections. If even, you are what your previously defined point is (inside or out) If odd, you are opposite of your defined point

https://en.wikipedia.org/wiki/Point_in_polygon should explain better!

Ralf
  • 538
  • 1
  • 6
  • 17
2

The point in polygon (PIP) is a well known problem in computational geometry. Wikipedia mentions two common solutions/algorithms, the Ray casting algorithm and the Winding number algorithm. You can try to implement them on your own or search for some library (the Java Topology Suite provides a solution for Java, there is a .NET port named NetTopologySuite).

Jan
  • 2,060
  • 2
  • 29
  • 34
1

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.

Community
  • 1
  • 1
Percy
  • 2,855
  • 2
  • 33
  • 56