Muhammad Umar
Muhammad Umar

Reputation: 11782

Finding a point in polygon in android

I am using the following code to find a point of coordinates exists in the code or not:

mMap.setOnMapClickListener(new OnMapClickListener() 
{
    public void onMapClick(LatLng point) 
    {
        boolean checkPoly = true;
        Point2D[] points = new Point2D[ myPoints.size()];
        for ( int i = 0; i < myPoints.size(); i ++)
        {
            LatLng pt = myPoints.get(i);
            points[i] = new Point2D(pt.latitude, pt.longitude);
        }
        Polygon2D polygon2d = new SimplePolygon2D(points);

        double a = point.latitude;
        double b = point.longitude;
        Point2D myPt = new Point2D(a,b);

        checkPoly = polygon2d.contains(myPt);
        Log.i("CHECK", String.valueOf(checkPoly));
        if (checkPoly)
        {
            setMarker(point);
        }
        else
            Toast.makeText(NewSearch.this,"The Location is outside of the Area", Toast.LENGTH_LONG).show();
    }

I am using the JavaGeom 0.11.1 library for finding polygon point. However this code was working exactly fine. Note that myPoints array is an ArrayList<LatLng> of all vertices of the polygons drawn on map. However something happened and now it's working for opposite that is outside of map; if i change !checkPoly then it works fine.

Does anyone know what is wrong?

Upvotes: 0

Views: 1820

Answers (2)

dwbrito
dwbrito

Reputation: 5254

I have been using Google android-maps-utils library and you can make use of the PolyUtil class, particularly at this method:

public static boolean containsLocation(LatLng point, List<LatLng> polygon, boolean geodesic)

Upvotes: 1

Gene
Gene

Reputation: 46960

I looked at the source for the polygon boundary definition. It's using the usual convention for "inside," which requires the vertices to be given in CCW order around the "inside" space. It's likely your boundary is given in CW order, which makes the "inside" what most people would call the outside.

In other words, what you think is a polygon is really a hole in the infinite polygon that covers the whole x-y universe.

So reverse the order of boundary vertices and things should start working as you intend.

ADDITION

If you can't reverse the order of vertices, there is a different polygon membership test that doesn't rely on point order. If you are testing membership of the point (x,y), this algorithm assumes that the point (infinity, y) is outside the polygon and then decides whether (x,y) is on the opposide side. The implementation here in C is due to WR Franklin. It would be easy to port this to Java. I've used it several times with excellent results.

Upvotes: 1

Related Questions