Calculating the area of a polygon
One of the recurring questions on GIS stackexchange is “What units is the area
calculated by JTS getArea()
”. It doesn’t seem to matter how many times people
say that these is no answer to this as it depends on the projection of your
data. The question will not die, so I cooked up some code that should give a
close-ish answer for most polygons.
As with most of these questions the trick is to convert your polygon to a flat
cartesian plane (this is where JTS works best). We can use the GeoTools auto
projection (assuming the polygon is small enough) and then simply call
.getArea()
method.
Note how I have returned a Measure
instead of a raw double, so now any one
using the method “knows” automatically that the answer is an area and it is in
square metres.
This is also handy if you want to display your result in another unit:
Produces this expected output, where we can use predefined units like Hectare (and the less common Are) and define our own units like kilometre squared and acre. According to QGIS identify it should be 103,888.317 km² for a large polygon.
For a smaller polygon I get 46.833 ha in QGIS and 46.901 ha which is close enough for most problems.