Saturday, 25 April 2015

ogr - Calculate total area of polygons in shapefile using GDAL?


I have a shapefile in British National Grid projection:


Geometry: 3D Polygon
Feature Count: 5378
Extent: (9247.520209, 14785.170099) - (638149.173223, 1217788.569952)
Layer SRS WKT:

PROJCS["British_National_Grid",
GEOGCS["GCS_airy",
DATUM["OSGB_1936",
SPHEROID["Airy_1830",6377563.396,299.3249646]],
PRIMEM["Greenwich",0],
UNIT["Degree",0.017453292519943295]],
PROJECTION["Transverse_Mercator"],
PARAMETER["latitude_of_origin",49],
PARAMETER["central_meridian",-2],
PARAMETER["scale_factor",0.9996012717],

PARAMETER["false_easting",400000],
PARAMETER["false_northing",-100000],
UNIT["Meter",1]]
cat: Integer (9.0)

Can I use GDAL/OGR to get the total area of all the polygons in the shapefile, in hectares?


I'm wondering if this is possible with -sql, something like:


ogrinfo -sql "SELECT SUM(ST_Area(geom::geography)) FROM mytable" myshapefile.shp

But trying that I get ERROR 1: Undefined function 'ST_Area' used..



I guess I could import the Shapefile into QGIS, add an area attribute to each polygon, and then sum it, but I would much rather use a command line tool if possible.



Answer



There's a special field in OGR SQL called OGR_GEOM_AREA which returns the area of the feature's geometry:


ogrinfo -sql "SELECT SUM(OGR_GEOM_AREA) AS TOTAL_AREA FROM myshapefile" myshapefile.shp

where TOTAL_AREA unit of measure depends by the layer SRS (read the comments below).


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...