Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);                
}
like image 855
Shudy Avatar asked Apr 04 '13 16:04

Shudy


People also ask

How do you check if a point is inside a polygon?

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.

Is a point inside or outside a polygon?

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.

What is point in polygon in GIS?

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.


2 Answers

You can use Google Maps PolyUtil:

import com.google.maps.android.PolyUtil;

boolean inside = PolyUtil.containsLocation(new LatLng(...), poly, true);
like image 68
fnieto - Fernando Nieto Avatar answered Oct 18 '22 13:10

fnieto - Fernando Nieto


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();
like image 42
Shudy Avatar answered Oct 18 '22 13:10

Shudy