确定点是否在多边形中

问题描述:

根据我的要求,我正在谷歌地图上绘制多边形,如下图所示.(使用地图 v2)

As per my requirement, I am drawing polygons on google map shown in the image below.(using maps v2)

现在我需要在用户输入特定多边形时显示警报.

Now I need to show an alert when user enters that particular polygons.

如何确定我的当前位置是否在多边形中.(需要优化的方式而不消耗电池)

How to identify if my current location is with in the polygon. (Need optimized way without draining battery)

提前致谢.

刚刚尝试了识别多边形中点的 Ray Casting 算法.这很完美.

Just tried Ray Casting algorithm which identifies point in polygon. This works perfect.

关于光线投射的论文,请参阅http://en.wikipedia.org/wiki/Point_in_polygon

Refer http://en.wikipedia.org/wiki/Point_in_polygon for thesis of Ray-Casting

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