I am trying to calculate the area covered by a polygon on a map in square kilometers. Based on the code from [1] and the corresponding paper [2] I have this code:
double area = 0;
auto coords = QList<QGeoCoordinate>{(QGeoCoordinate(50.542908183, 6.2521438908), QGeoCoordinate(50.250550175, 6.2521438908), QGeoCoordinate(50.250550175, 6.4901310043), QGeoCoordinate(50.542908183, 6.4901310043))};
for(int i=0; i<coords.size()-1; i++)
{
const auto &p1 = coords[i];
const auto &p2 = coords[i+1];
area += qDegreesToRadians(p2.longitude() - p1.longitude()) *
(2 + qSin(qDegreesToRadians(p2.latitude())) +
qSin(qDegreesToRadians(p1.latitude())));
}
area = area * 6378137.0 * 6378137.0 / 2.0;
qDebug() << "Area:" << (area/1000000);
qDebug() << coords;
But the calculated area is completely wrong. Also moving the polyon's vertices around results in strange results: Depending on the vertex the calculated area gets smaller althought the polgon's area is increased and vice verse. The calculated area also seems to depend on which vertex is used as start vertex.
Interestingly the signed are of a ring algorithm (getArea
from [1]) returns correct results, meaning that the calculated area increases/decreases when the polygon's size is changed.
The code for calculating the area on a sphere was also used elsewhere so I am pretty sure that something is wrong with my implementation.
[1] https://github.com/openlayers/openlayers/blob/v2.13.1/lib/OpenLayers/Geometry/LinearRing.js#L251