- QGIS Python Programming Cookbook
- Joel Lawhead
- 354字
- 2021-07-23 19:48:54
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:
- First, load the layer:
lyr = QgsVectorLayer("/qgis_data/nyc/NYC_MUSEUMS_GEO.shp", "Museums", "ogr")
- Next, visualize the layer on the map:
QgsMapLayerRegistry.instance().addMapLayers([lyr])
- Access the layer's features:
fts = lyr.getFeatures()
- Grab the first feature:
ft = fts.next()
- Select this feature:
lyr.setSelectedFeatures([ft.id()])
- Create the buffer:
buff = ft.geometry().buffer(.2,8)
- Set up a memory layer for the buffer's geometry:
buffLyr = QgsVectorLayer('Polygon?crs=EPSG:4326', 'Buffer' , 'memory')
- Access the layer's data provider:
pr = buffLyr.dataProvider()
- Create a new feature:
b = QgsFeature()
- Set the feature's geometry with the buffer geometry:
b.setGeometry(buff)
- Add the feature to the data provider:
pr.addFeatures([b])
- Update the buffer layer's extents:
buffLyr.updateExtents()
- Set the buffer layer's transparency so that you can see other features as well:
buffLyr.setLayerTransparency(70)
- Add the buffer layer to the map:
QgsMapLayerRegistry.instance().addMapLayers([buffLyr])
Verify that your map looks similar to this screenshot:

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.
- CMDB分步構建指南
- LabVIEW2018中文版 虛擬儀器程序設計自學手冊
- Instant Apache Stanbol
- Learning Spring 5.0
- 劍指JVM:虛擬機實踐與性能調優
- C和C++安全編碼(原書第2版)
- Scratch 3.0少兒編程與邏輯思維訓練
- 人臉識別原理及算法:動態人臉識別系統研究
- PySide GUI Application Development(Second Edition)
- Visual FoxPro程序設計
- Selenium Testing Tools Cookbook(Second Edition)
- 基于SpringBoot實現:Java分布式中間件開發入門與實戰
- MySQL 8從零開始學(視頻教學版)
- Kotlin進階實戰
- Python Machine Learning Cookbook