Geometry in Plan (Math)

84 Views Asked by At

My problem is to know whether or not a point is contained in a polygon (sets of points) on the same surface.

Simple example in my favorite language DART

Point myPoint = new Point(10, 12);

List<Point> myPolygon = [ // The Polygon, for example is simple rect
  new Point(2, 7),
  new Point(15,7),
  new Point(15, 18),
  new Point(2, 18)
];

bool pointIsContainedInPolygon(List Polygon){
  // .. data processing ...
}

I need to know what is the function: pointIsContainedInPolygon(myPolygon)

1

There are 1 best solutions below

1
On BEST ANSWER

I have resumed the code data in the How can I determine whether a 2D Point is within a Polygon? post in dart, here is the result (tested)

bool pnpoly(Point point, List<Point> polygon){
    // Step 1: Cut and detail

    int nvert = polygon.length;
    List<int> vertx = [];
    List<int> verty = [];

    for(Point vert in polygon){ // Listing x and y pos of all vertices
        vertx.add(vert.x);
        verty.add(vert.y);
    }

    // Step 2: Calcul..
    bool c = false;
    int j = nvert-1;
    for (int i = 0; i < nvert; j = i++){    
        if( ((verty[i]>point.y) != (verty[j]>point.y)) && (point.x < (vertx[j]-vertx[i]) * (point.y-verty[i]) / (verty[j]-verty[i]) + vertx[i]) ){
            c = !c;
        }
    }
    return c;
}

Here is my test

List<Point> myPolygon = [ // classic rectangle
    new Point(2,2),
    new Point(52,2),
    new Point(52,41),
    new Point(2,41)
];

Point myPoint = new Point(53,40);

print( pnpoly(myPoint, myPolygon) ); // false