安卓地理围栏(多边形)

11
如何从多个地理位置(经度、纬度值)创建多边形地理围栏。同时,在Android上如何跟踪用户进入或退出该围栏区域。
2个回答

20

地理围栏是由一组经度和纬度点构成的多边形。当你有了这些点的列表后,可以使用“点在多边形内”检查函数来确定一个位置是否在多边形内。

以下是我在自己的项目中使用的代码,用于对非常大的凹多边形(20K+顶点)进行点在多边形内的检查:

public class PolygonTest
{
    class LatLng
    {
        double Latitude;
        double Longitude;

        LatLng(double lat, double lon)
        {
            Latitude = lat;
            Longitude = lon;
        }
    }

    bool PointIsInRegion(double x, double y, LatLng[] thePath)
    {
        int crossings = 0;

        LatLng point = new LatLng (x, y);
        int count = thePath.length;
        // for each edge
        for (var i=0; i < count; i++) 
        {
            var a = thePath [i];
            var j = i + 1;
            if (j >= count) 
            {
                j = 0;
            }
            var b = thePath [j];
            if (RayCrossesSegment(point, a, b)) 
            {
                crossings++;
            }
        }
        // odd number of crossings?
        return (crossings % 2 == 1);
    }

    bool RayCrossesSegment(LatLng point, LatLng a, LatLng b)
    {
        var px = point.Longitude;
        var py = point.Latitude;
        var ax = a.Longitude;
        var ay = a.Latitude;
        var bx = b.Longitude;
        var by = b.Latitude;
        if (ay > by)
        {
            ax = b.Longitude;
            ay = b.Latitude;
            bx = a.Longitude;
            by = a.Latitude;
        }
            // alter longitude to cater for 180 degree crossings
        if (px < 0) { px += 360; };
        if (ax < 0) { ax += 360; };
        if (bx < 0) { bx += 360; };

        if (py == ay || py == by) py += 0.00000001;
        if ((py > by || py < ay) || (px > Math.max(ax, bx))) return false;
        if (px < Math.min(ax, bx)) return true;

        var red = (ax != bx) ? ((by - ay) / (bx - ax)) : float.MAX_VALUE;
        var blue = (ax != px) ? ((py - ay) / (px - ax)) : float.MAX_VALUE;
        return (blue >= red);
    }
}

从程序流程上看,您需要一个后台服务来进行位置更新,并针对您的经纬度多边形数据执行此检查以查看该位置是否在内部。


地理围栏也可以是凸多边形。我已经写了一个地理围栏的 PHP 类。 - Micromega
1
啊,我写错了,是吧?谢谢你指出来。 - matthewrdev
1
在我看来,这是纯金。它有任何实际的限制、缺陷或不准确之处吗?此外,这个算法有一个名称吗? - LucasM

4

如果人们仍在寻找多边形地理围栏检查,您可以使用GoogleMaps.Util.PolyUtilcontainsLocation方法完成。


实现 'com.google.maps.android:android-maps-utils:0.5' - Rasel

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