3

Google Maps Api has a google.maps.geometry.spherical.computeArea method. How can I write its equivalent in C#? (What will be the formula)

I have a set of lat long values for which I need to calculate area (in meters) of the enclosed polygon.

Sample code is highly appreciated.

Muhammad Hasan Khan
  • 34,648
  • 16
  • 88
  • 131

3 Answers3

4

Sorry for adding an answer to an old question, but if someone else is looking for a quickly answer:

private const double EARTH_RADIUS = 6378137;

public class LatLng
{
    public double latitude { get; private set; }
    public double longitude { get; private set; }

    public LatLng(double latitude, double longitude)
    {
        this.latitude = latitude;
        this.longitude = longitude;
    }
}

public static double computeArea(List<LatLng> path)
{
    return Math.Abs(computeSignedArea(path));
}

private static double computeSignedArea(List<LatLng> path, double radius = EARTH_RADIUS)
{
    int size = path.Count;
    if (size < 3) { return 0; }
    double total = 0;
    LatLng prev = path[size - 1];
    double prevTanLat = Math.Tan((Math.PI / 2 - toRadians(prev.latitude)) / 2);
    double prevLng = toRadians(prev.longitude);
    // For each edge, accumulate the signed area of the triangle formed by the North Pole
    // and that edge ("polar triangle").
    foreach (LatLng point in path)
    {
        double tanLat = Math.Tan((Math.PI / 2 - toRadians(point.latitude)) / 2);
        double lng = toRadians(point.longitude);
        total += polarTriangleArea(tanLat, lng, prevTanLat, prevLng);
        prevTanLat = tanLat;
        prevLng = lng;
    }
    return total * (radius * radius);
}

private static double polarTriangleArea(double tan1, double lng1, double tan2, double lng2)
{
    double deltaLng = lng1 - lng2;
    double t = tan1 * tan2;
    return 2 * Math.Atan2(t * Math.Sin(deltaLng), 1 + t * Math.Cos(deltaLng));
}

private static double toRadians(double input)
{
    return input * Math.PI / 180;
}

Reference https://github.com/googlemaps

Ric.H
  • 489
  • 4
  • 12
0

What have you tried yourself?

There are some very similar questions with detailed answers, so it's best to refer to them:

Community
  • 1
  • 1
Kasaku
  • 2,192
  • 16
  • 26
  • I want equivalent of that method. Can't try something until I know whats going on in that method. Which projection it is using etc. I have already written a method but results are different and this questions is not about whats wrong with my implementation but rather what is going on inside that method if someone knows. – Muhammad Hasan Khan Oct 04 '11 at 11:46
  • Refer to the links which are answering the same problem you are facing. I don't think the exact algorithm that Google uses is stated anywhere. – Kasaku Oct 04 '11 at 11:50
-1

You can get the formula from Wikipedia.

Greg B
  • 14,597
  • 18
  • 87
  • 141