检查Latlng是否在多边形内部

3

我正在城市中绘制多边形,以检查当前位置是否在此多边形内部。我使用以下代码:

 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));

我通过以下方式检查当前位置是否在此多边形内:

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());
    }

这是我的isPointInPolygon方法:

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;
}

我不知道为什么它没有工作,这里错过了什么?

2个回答

4

我不知道为什么你的代码没有起作用。

但是你可以使用PolyUtil.containsLocation (new LatLng (latitude, longitude), polyLoc, true)

如果位置在多边形外面,这会返回false。


在我的情况下,无论是内部还是外部,它始终返回 true,不知道为什么。 - Muhammad Noman
是的。我已将数组的第一个点也添加到了最后,使其闭合。这个方法可行。谢谢。 - Muhammad Noman
@MuhammadNoman 不用谢,如果觉得回答有帮助,请随意点赞。 - user6490462

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接