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.
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.
This recipe involves both a spatial operation and multiple visualizations. To do this, perform the following steps:
lyr = QgsVectorLayer("/qgis_data/nyc/NYC_MUSEUMS_GEO.shp", "Museums", "ogr")
QgsMapLayerRegistry.instance().addMapLayers([lyr])
fts = lyr.getFeatures()
ft = fts.next()
lyr.setSelectedFeatures([ft.id()])
buff = ft.geometry().buffer(.2,8)
buffLyr = QgsVectorLayer('Polygon?crs=EPSG:4326', 'Buffer' , 'memory')
pr = buffLyr.dataProvider()
b = QgsFeature()
b.setGeometry(buff)
pr.addFeatures([b])
buffLyr.updateExtents()
buffLyr.setLayerTransparency(70)
QgsMapLayerRegistry.instance().addMapLayers([buffLyr])
Verify that your map looks similar to this screenshot:
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.