Python – Creating Convex Hull and Buffer for Selected Features Using Python

pyqgisqgis-2qgis-plugins

I have features selected on the mapcanvas. I want to perform convex hull for those selected features and save those in a memory or store it in a variable preferably and then want to do buffer for the resultant convex hull using python in QGIS.

layer = iface.activeLayer()
features = layer.selectedFeatures()
convex_hull = QgsGeometryAnalyzer().convexHull(layer, path.shp, True, -1, p-None)

The above convexhull function exports the result to a layer but doesnt store. How this can be done?

Best Answer

This code works well. I used it with a point shapefile (Multi Part) for getting its convexHull Polygon.

layer = iface.activeLayer()
feat = layer.selectedFeatures()[0]

#get geometry
geom = feat.geometry()

convexhull = geom.convexHull()

#Extract CRS from layer
CRS = layer.crs().postgisSrid()

URI = "Polygon?crs=epsg:"+str(CRS)+"&field=id:integer""&index=yes"

#Create polygon layer for convexHull
mem_layer = QgsVectorLayer(URI,
                        "convexhull",
                        "memory")

#add Map Layer to Registry
QgsMapLayerRegistry.instance().addMapLayer(mem_layer)

#Prepare mem_layer for editing
mem_layer.startEditing()

#Set feature for convexHull
feat2 = QgsFeature()

#Set geometry for convexHull
feat2.setGeometry(convexhull)

#set attributes values for convexHull
feat2.setAttributes([1])

mem_layer.addFeature(feat2, True)

#stop editing and save changes
mem_layer.commitChanges()

iface.mapCanvas().refresh()

Before running the code in the Python Console (selected features in default yellow color):

enter image description here

After running the code:

enter image description here

Convexhull is a memory layer and it can be saved as shapefile in the directory that you prefer or be used to do a buffer in the same script. Automatically, convexhull becomes the active layer.

Related Question