Following piece of java code is a solution to determine whether a 2D Point is within a Polygon or not (taken from here). I think this code has some problems. For example for this polygon:
Point[] polygon = new Point[5];
polygon[0] = new Point(30,20);
polygon[1] = new Point(80,10);
polygon[2] = new Point(75,100);
polygon[3] = new Point(40,100);
polygon[4] = new Point(55,65);
It returns true (inside) for (76,82) but this point is on the edge (Code returns false correctly for another point on the edge : (45,17)). Also it returns false (not inside) for (45,90) but it is inside of the polygon. What is the problem?
public boolean IsPointInPolygon(Point p, Point[] polygon)
{
double minX = polygon[0].x;
double maxX = polygon[0].x;
double minY = polygon[0].y;
double maxY = polygon[0].y;
for ( int i = 1 ; i < polygon.length; i++ )
{
Point q = polygon[i];
minX = Math.min(q.x, minX);
maxX = Math.max(q.x, maxX);
minY = Math.min(q.y, minY);
maxY = Math.max(q.y, maxY);
}
if ( p.x <= minX || p.x >= maxX || p.y <= minY || p.y >= maxY )
{
return false;
}
boolean inside = false;
int j = polygon.length - 1;
for (int i = 0 ;i < polygon.length ; j = i++)
{
if (( polygon[i].y > p.y ) != ( polygon[j].y > p.y) &&
p.x <= (polygon[j].x - polygon[i].x ) * ( p.y - polygon[i].y ) / ( polygon[j].y - polygon[i].y ) + polygon[i].x)
{
inside = !inside;
}
}
return inside;
}
I think I should change my code to below, but I am not sure !
float tempX = ((float)((polygon[i].x - polygon[j].x) * (p.y - polygon[i].y)) / (polygon[i].y - polygon[j].y)) + polygon[i].x;
if (p.x < tempX) {
inside = !inside;
}
else if (p.x == tempX) {
return false;
}
This algorithm
if ( p.x <= minX || p.x >= maxX || p.y <= minY || p.y >= maxY )
{
return false;
}
Is wrong. It only checks if the point is within a rectangle, bounded by minX, maxX, minY, maxY
You can't test if a point is within a polygon without using all the polygon vertices.
Use java.awt.Polygon :
public boolean isPointInPolygon(Point p, Point[] points)
{
Polygon polygon = new Polygon();//java.awt.Polygon
for(Point point : points) {
polygon.addPoint(point.x, point.y);
}
return polygon.contains(p);
}
Testing it with
Point[] points = new Point[5];
points[0] = new Point(30,20);
points[1] = new Point(80,10);
points[2] = new Point(75,100);
points[3] = new Point(40,100);
points[4] = new Point(55,65);
System.out.println(isPointInPolygon(new Point(76,82), points) );
prints out false.