检查坐标是否位于多边形内 c#

时间:2021-01-01 14:00:18

标签: c# .net google-maps math

我正在使用代码来检查坐标是否位于多边形内,但是每当我测试靠近边界的坐标时,例如 300 米,它有时会返回 true,有时会返回 false。

下面是我正在使用的功能

  public static bool IsPointInPolygon2(SentinelLocation[] polygon,SentinelLocation p)
    {
        double minX = polygon[0].Longitude;
        double maxX = polygon[0].Longitude;
        double minY = polygon[0].Latitude;
        double maxY = polygon[0].Latitude;
        for (int i = 1; i < polygon.Length; i++)
        {
            SentinelLocation q = polygon[i];
            minX = Math.Min(q.Longitude, minX);
            maxX = Math.Max(q.Longitude, maxX);
            minY = Math.Min(q.Latitude, minY);
            maxY = Math.Max(q.Latitude, maxY);
        }

        if (p.Longitude < minX || p.Longitude > maxX || p.Latitude < minY || p.Latitude > maxY)
        {
            return false;
        }

        // https://wrf.ecse.rpi.edu/Research/Short_Notes/pnpoly.html
        bool inside = false;
        for (int i = 0, j = polygon.Length - 1; i < polygon.Length; j = i++)
        {
            if ((polygon[i].Latitude > p.Latitude) != (polygon[j].Latitude > p.Latitude) &&
                 p.Longitude < (polygon[j].Longitude - polygon[i].Longitude) * (p.Latitude - polygon[i].Latitude) / (polygon[j].Latitude - polygon[i].Latitude) + polygon[i].Longitude)
            {
                inside = !inside;
            }
        }

        return inside;
    }

这是我正在传递的测试数据

 public bool IsInsidePolyGon(double latitude,double longitude)
    {
        var location = new SentinelLocation
        {
            Latitude = latitude,
            Longitude = longitude,
        };
        var polygon = new List<SentinelLocation>();
        polygon.Add(new SentinelLocation
        {
            Latitude = 31.82703,
            Longitude = 63.23671
        });
        polygon.Add(new SentinelLocation
        {
            Latitude = 34.54806,
            Longitude = 61.91835
        });

        polygon.Add(new SentinelLocation
        {
            Latitude = 35.37638,
            Longitude = 67.32363
        });
        polygon.Add(new SentinelLocation
        {
            Latitude = 32.71876,
            Longitude = 67.19179
        });
      

        var toReturn = PolyUtil.IsPointInPolygon2(polygon.ToArray(),location);
        return toReturn;
    }

失败的测试用例是纬度:34.96946 和经度 64.66381

我的多边形看起来像这样

enter image description here

谁能指导我这里出了什么问题?

0 个答案:

没有答案