Calculate the area of a polygon with latitude and longitude

不羁的心 提交于 2019-11-27 22:47:59

问题


I have this code, written using this: source1 and this: source 2

public static double CalculatePolygonArea(IList<GpsLocation> coordinates)
    {
        double area = 0;

        if (coordinates.Count > 2)
        {
            for (var i = 0; i < coordinates.Count-1; i++)
            {
                GpsLocation p1, p2;
                p1 = coordinates[i];
                p2 = coordinates[i + 1];
                area += ToRad(p2.Longitude - p1.Longitude) * (2 + Math.Sin(ToRad(p1.Latitude))
                   + Math.Sin(ToRad(p2.Latitude)));

                area = area * R * R / 2;
            }
        }

        return Math.Abs(area);
    }

Here is my test code:

[Fact]
    public void GpsPolygonAreaTest()
    {
        var poly = new List<GpsLocation>();
        var p1 = new GpsLocation(0, 0);
        poly.Add(p1);
        var p2 = GpsHelper.CreateLocationBasedOnBearingDistance(p1, 5, 100);
        poly.Add(p2);
        var p3 = GpsHelper.CreateLocationBasedOnBearingDistance(p2, 95, 100);
        poly.Add(p3);
        var p4 = GpsHelper.CreateLocationBasedOnBearingDistance(p3, 185, 100);
        poly.Add(p4);
        poly.Add(p1);

        var area = GpsHelper.CalculatePolygonArea(poly);

        area.Should().Be(10000);
    }

I confirmed that my polygon is 100m x 100m, see image:

My test result is: Expected value to be 10000, but found 1.28153883377486E+48.

Any ideas what wrong with my code?


回答1:


I'm pretty sure this statement:

area = area * R * R / 2;

should be placed after the loop over the vertices, rather than repeated on each iteration.



来源:https://stackoverflow.com/questions/36022883/calculate-the-area-of-a-polygon-with-latitude-and-longitude

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!