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

Buffering a feature intermediate

Buffering a feature creates a polygon around a feature as a selection geometry or just a simple visualization. In this recipe, we'll buffer a point in a point feature and add the returned polygon geometry to the map.

Getting ready

Once again, we'll use the same New York City Museums layer. You can download the layer from https://geospatialpython.googlecode.com/svn/NYC_MUSEUMS_GEO.zip.

Unzip that file and place the shapefile's contents in a directory named nyc within your qgis_data directory, within your root or home directory.

How to do it...

This recipe involves both a spatial operation and multiple visualizations. To do this, perform the following steps:

  1. First, load the layer:
    lyr = QgsVectorLayer("/qgis_data/nyc/NYC_MUSEUMS_GEO.shp", "Museums", "ogr")
    
  2. Next, visualize the layer on the map:
    QgsMapLayerRegistry.instance().addMapLayers([lyr])
    
  3. Access the layer's features:
    fts = lyr.getFeatures()
    
  4. Grab the first feature:
    ft = fts.next()
    
  5. Select this feature:
    lyr.setSelectedFeatures([ft.id()])
    
  6. Create the buffer:
    buff = ft.geometry().buffer(.2,8)
    
  7. Set up a memory layer for the buffer's geometry:
    buffLyr = QgsVectorLayer('Polygon?crs=EPSG:4326', 'Buffer' , 'memory')
    
  8. Access the layer's data provider:
    pr = buffLyr.dataProvider()
    
  9. Create a new feature:
    b = QgsFeature()
    
  10. Set the feature's geometry with the buffer geometry:
    b.setGeometry(buff)
    
  11. Add the feature to the data provider:
    pr.addFeatures([b])
    
  12. Update the buffer layer's extents:
    buffLyr.updateExtents()
    
  13. Set the buffer layer's transparency so that you can see other features as well:
    buffLyr.setLayerTransparency(70)
    
  14. Add the buffer layer to the map:
    QgsMapLayerRegistry.instance().addMapLayers([buffLyr])
    

Verify that your map looks similar to this screenshot:

How to do it...

How it works...

The interesting portion of this recipe starts with Step 6, which creates the buffer geometry. The parameters for the buffer() method are the distance in map units for the buffer followed by the number of straight line segments used to approximate curves. The more segments you specify, the more the buffer appears like a circle. However, more segments equals greater geometric complexity and therefore slower rendering, as well as slower geometry calculations. The other interesting feature of this recipe is Step 13, in which we set the transparency of the layer to 70 percent. We also introduce the way to create a new layer, which is done in memory. Later chapters will go more in depth on creating data.

主站蜘蛛池模板: 广州市| 勐海县| 鄂尔多斯市| 广水市| 长泰县| 普兰店市| 舟曲县| 大安市| 无锡市| 卢氏县| 东乡族自治县| 西昌市| 银川市| 鹤岗市| 鹿邑县| 石阡县| 西贡区| 翼城县| 宁远县| 库车县| 河津市| 公安县| 喜德县| 安图县| 攀枝花市| 外汇| 稷山县| 宝清县| 江阴市| 内丘县| 邢台县| 乡宁县| 陕西省| 六枝特区| 罗江县| 泰兴市| 扎鲁特旗| 类乌齐县| 洛隆县| 德清县| 八宿县|