- QGIS Python Programming Cookbook
- Joel Lawhead
- 249字
- 2021-07-23 19:48:55
Calculating the area of a polygon
This recipe simply measures the area of a polygon.
Getting ready
For this recipe, we'll use a single-feature polygon shapefile, which you can download from https://geospatialpython.googlecode.com/files/Mississippi.zip
Unzip the shapefile and put it in a directory named qgis_data/ms within your root or home directory.
How to do it...
Perform the following steps to measure the area of a large polygon:
- First, import the QGIS constants library, as follows:
from qgis.core import QGis
- Load the layer:
lyr = QgsVectorLayer("/qgis_data/ms/mississippi.shp", "Mississippi", "ogr")
- Access the layer's features:
fts = lyr.getFeatures()
- Get the boundary feature:
boundary = fts.next()
- Create the measurement object instance:
d = QgsDistanceArea()
- Pass the polygon list to the
measureArea()
method:m = d.measurePolygon(boundary.geometry().asPolygon()[0])
- Convert the measurement from decimal degrees to miles:
d.convertMeasurement(m, QGis.Degrees, QGis.NauticalMiles, True)
- Verify that your output looks similar to the following:
(42955.47889640281, 7)
How it works...
PyQIS has no measureArea()
method, but it has a measurePolygon()
method in the QgsDistanceArea
object. The method accepts a list of points. In this case, when we convert the measurement output from decimal degrees to miles, we also specify True
in the convertMeasurement()
method so that QGIS knows that it is an area calculation. Note that when we get the boundary geometry as a polygon, we use an index of 0, suggesting that there is more than one polygon. A polygon geometry can have inner rings, which are specified as additional polygons. The outermost ring, in this case the only ring, is the first polygon.
- LabVIEW 2018 虛擬儀器程序設(shè)計
- Mastering Zabbix(Second Edition)
- Python程序設(shè)計(第3版)
- Building a Recommendation Engine with Scala
- Java Web應(yīng)用開發(fā)技術(shù)與案例教程(第2版)
- 小程序,巧運營:微信小程序運營招式大全
- Learning Salesforce Einstein
- 硅谷Python工程師面試指南:數(shù)據(jù)結(jié)構(gòu)、算法與系統(tǒng)設(shè)計
- 深度學(xué)習(xí)原理與PyTorch實戰(zhàn)(第2版)
- 小程序從0到1:微信全棧工程師一本通
- Python開發(fā)基礎(chǔ)
- Learning Image Processing with OpenCV
- Web開發(fā)新體驗
- 計算機(jī)輔助設(shè)計與繪圖技術(shù)(AutoCAD 2014教程)(第三版)
- R Data Visualization Cookbook