Shudy Shudy - 1 year ago 88
Android Question

Test of Point inside polygon in Android

The other day I did a class in Java to calculate if a

point(X,Y)
is inside a polygon. (
X
and
Y
are
double
, because will be geo-coordinates).

I know that Java has the class
Polygon
, but I had to use
Path2D
and
Point2D
, because
Polygon
don't allow
double
's, just integers :(

Once I have the polygon done in
Path2D
, I used the method
contains
(
Path2D
had it), and my problem was solved.

But now, I want to import to Android, and the problem is here, because
Path2D
needs to import:

import java.awt.geom.Path2D;
import java.awt.geom.Point2D;


and in Android don't exist awt, so I can't use.

So, is there any class similar to
Path2D
that had
contains
method? or I have to calculate by myself?

Here is how I did in Java using
Path2D
:

private void ConstructPolygon(Vector<Point2D> coodinates)
{
this.polygon.moveTo(coodinates.get(0).getX(), coodinates.get(0).getY());

//System.out.println(coodinates.get(0).getX() + " " + coodinates.get(0).getY());
//System.out.println("asda");

for(int i = 1; i < this.num_points; i++)
{
//System.out.println(coodinates.get(i).getX() + " " + coodinates.get(i).getY());
this.polygon.lineTo(coodinates.get(i).getX(), coodinates.get(i).getY());
}
this.polygon.closePath();
}
public boolean InsideCity(Point2D punto)
{
return this.polygon.contains(punto);
}

Answer Source

You can use my simple library exactly for this: https://github.com/sromku/polygon-contains-point.

Prepare polygon:

Polygon polygon = Polygon.Builder()
    .addVertex(new Point(1, 3))
    .addVertex(new Point(2, 8))
    .addVertex(new Point(5, 4))
    .addVertex(new Point(5, 9))
    .addVertex(new Point(7, 5))
    .addVertex(new Point(6, 1))
    .addVertex(new Point(3, 1))
    .build();

And check whereas the point is inside the polygon:

Point point = new Point(4.5f, 7);
boolean contains = polygon.contains(point);

It works with float types and with polygons that contain holes :)