check if Latlng is inside polygon

3.3k Views Asked by At

I'm drawing Polygon on city in order to check if current position is inside this polygon or not, and i'm doing that with below code:-

 ArrayList<LatLng> polyLoc = new ArrayList<LatLng>();
polyLoc.add(new LatLng(24.643932, 46.297718));
    polyLoc.add(new LatLng(24.695098, 46.555897));
    polyLoc.add(new LatLng(24.921971, 46.476246));
    polyLoc.add(new LatLng(25.147185, 46.366383));
    polyLoc.add(new LatLng(25.155886, 47.249409));
    polyLoc.add(new LatLng(24.929444, 47.346913));
    polyLoc.add(new LatLng(24.691355, 47.106587));
    polyLoc.add(new LatLng(24.449060, 47.219197));
    polyLoc.add(new LatLng(24.293947, 46.973377));
    polyLoc.add(new LatLng(24.641436, 46.299092));

And i checking if the current position is inside this polygon or not by this way :-

if (hasPermission() && gpsTracker.canGetLocation()) {
        if (isPointInPolygon(new LatLng(gpsTracker.getLatitude(), gpsTracker.getLongitude()), polyLoc)) {
            cash.setVisibility(View.VISIBLE);
            cashIcon.setVisibility(View.VISIBLE);
        } else {
            cash.setVisibility(View.GONE);
            cashIcon.setVisibility(View.GONE);
        }
        Log.d(TAG, "reservationDialog: " + gpsTracker.getLatitude() + gpsTracker.getLongitude());
    }

here is my isPointInPolygon method :

private boolean isPointInPolygon(LatLng tap, ArrayList<LatLng> vertices) {
    int intersectCount = 0;
    for (int j = 0; j < vertices.size() - 1; j++) {
        if (rayCastIntersect(tap, vertices.get(j), vertices.get(j + 1))) {
            intersectCount++;
        }
    }

    return ((intersectCount % 2) == 1); // odd = inside, even = outside;
}

private boolean rayCastIntersect(LatLng tap, LatLng vertA, LatLng vertB) {

    double aY = vertA.latitude;
    double bY = vertB.latitude;
    double aX = vertA.longitude;
    double bX = vertB.longitude;
    double pY = tap.latitude;
    double pX = tap.longitude;

    if ((aY > pY && bY > pY) || (aY < pY && bY < pY)
            || (aX < pX && bX < pX)) {
        return false; // a and b can't both be above or below pt.y, and a or
        // b must be east of pt.x
    }

    double m = (aY - bY) / (aX - bX); // Rise over run
    double bee = (-aX) * m + aY; // y = mx + b
    double x = (pY - bee) / m; // algebra is neat!

    return x > pX;
}

I don't know why it's not working, what i'v missed here?

2

There are 2 best solutions below

3
On BEST ANSWER

I don't know why your code didn't work.

But you can use PolyUtil.containsLocation (new LatLng (latitude, longitude), polyLoc, true)

This would return false if the position outside the polygon.

0
On

In my project, I'm doing this calculation on the server. I'm using geolib library to do this. If you need to calculate in your app. You can get the logic from the library.

Library: https://www.npmjs.com/package/geolib

Git: https://github.com/manuelbieh/Geolib