官术网_书友最值得收藏!

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:

  1. First, import the QGIS constants library, as follows:
    from qgis.core import QGis
    
  2. Load the layer:
    lyr = QgsVectorLayer("/qgis_data/ms/mississippi.shp", "Mississippi", "ogr")
    
  3. Access the layer's features:
    fts = lyr.getFeatures()
    
  4. Get the boundary feature:
    boundary = fts.next()
    
  5. Create the measurement object instance:
    d = QgsDistanceArea()
    
  6. Pass the polygon list to the measureArea() method:
    m = d.measurePolygon(boundary.geometry().asPolygon()[0])
    
  7. Convert the measurement from decimal degrees to miles:
    d.convertMeasurement(m, QGis.Degrees, QGis.NauticalMiles, True) 
    
  8. 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.

主站蜘蛛池模板: 鹿邑县| 玉环县| 奈曼旗| 胶南市| 柏乡县| 驻马店市| 凤阳县| 酉阳| 隆德县| 贵阳市| 常山县| 秭归县| 湘潭市| 玛沁县| 博爱县| 湖口县| 白朗县| 中超| 宁城县| 洪江市| 贵南县| 潞城市| 鄂州市| 永济市| 鄯善县| 江达县| 自治县| 清远市| 东源县| 开阳县| 容城县| 大埔区| 晋宁县| 广东省| 晋州市| 高尔夫| 汉中市| 大竹县| 宣恩县| 秭归县| 罗定市|