3

I need to implement Geofence in C#. Geofence area can be round, rectangle, polygon etc. Does anyone have Geofence implementation in C#?

I found Geo Fencing - point inside/outside polygon. But, it supports polygon only.

Community
  • 1
  • 1
Let me Ask
  • 1,029
  • 1
  • 8
  • 33
  • The polygon trivially contains the rectangle as a special case(provided you manage to define what a rectangle on a sphere actually is). And circles can be checked with pythagoras' theorem. – CodesInChaos Mar 18 '11 at 13:26

2 Answers2

6

I have tested various implementations and this example worked properly for me:

Example

public static bool PolyContainsPoint(List<Point> points, Point p) {
    bool inside = false;

    // An imaginary closing segment is implied,
    // so begin testing with that.
    Point v1 = points[points.Count - 1];

    foreach (Point v0 in points)
    {
        double d1 = (p.Y - v0.Y) * (v1.X - v0.X);
        double d2 = (p.X - v0.X) * (v1.Y - v0.Y);

        if (p.Y < v1.Y)
        {
            // V1 below ray
            if (v0.Y <= p.Y)
            {
                // V0 on or above ray
                // Perform intersection test
                if (d1 > d2)
                {
                    inside = !inside; // Toggle state
                }
            }
        }
        else if (p.Y < v0.Y)
        {
            // V1 is on or above ray, V0 is below ray
            // Perform intersection test
            if (d1 < d2)
            {
                inside = !inside; // Toggle state
            }
        }

        v1 = v0; //Store previous endpoint as next startpoint
    }

    return inside; 
}
Chun Lin
  • 534
  • 14
  • 31
Fábio Nascimento
  • 2,479
  • 1
  • 20
  • 26
1

Refer to my Implementation:

Polygon

Circle

Community
  • 1
  • 1
Let me Ask
  • 1,029
  • 1
  • 8
  • 33