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);
}
Draw a horizontal line to the right of each point and extend it to infinity. Count the number of times the line intersects with polygon edges. A point is inside the polygon if either count of intersections is odd or point lies on an edge of polygon. If none of the conditions is true, then point lies outside.
If the number of times this ray intersects the line segments making up the polygon is even then the point is outside the polygon. Whereas if the number of intersections is odd then the point (xp,yp) lies inside the polygon.
In computational geometry, the point-in-polygon (PIP) problem asks whether a given point in the plane lies inside, outside, or on the boundary of a polygon.
You can use Google Maps PolyUtil:
import com.google.maps.android.PolyUtil;
boolean inside = PolyUtil.containsLocation(new LatLng(...), poly, true);
Sorry @sromku I asked my self (I never used this type of things)
That's how I solved if anyone have the same question
Builder poly2 = new Polygon.Builder();
for(int i = 0; i< xpoints.length;i++){
poly2.addVertex(new Point(xpoints[i],ypoints[i]));
}
Polygon polygon2 = poly2.build();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With