Saturday, 31 October 2015

line - Selecting features within certain buffer distance of selected feature using PyQGIS?


I have a shapefile of thousands of polylines. I have select one feature, I want to select all other features that is within say 100m of the selected feature.


How do I achieve it by pyqgis?


enter image description here



Answer




If you want to select all features that are within 100 m of the selected "buffer" feature you can use next code:


layer = iface.activeLayer()

feats = [ feat for feat in layer.getFeatures() ]

#selected feature fid = 0
geom_buffer = feats[0].geometry().buffer(100, -1)

#erasing selected feature in original list
del feats[0]


new_feats = [feat for feat in feats
if feat.geometry().intersects(geom_buffer) ]

epsg = layer.crs().postgisSrid()

uri = "LineString?crs=epsg:" + str(epsg) + "&field=id:integer""&index=yes"

mem_layer = QgsVectorLayer(uri,
'line',

'memory')

prov = mem_layer.dataProvider()

for i, feat in enumerate(new_feats):
feat.setAttributes([i])

prov.addFeatures(new_feats)

QgsMapLayerRegistry.instance().addMapLayer(mem_layer)


It produces a memory layer with features that match this condition.


I tried out above code with next line layer; where selected feature (id=0) was previously visualized as buffer by using its WKT format into QuickWKT plugin of QGIS.


enter image description here


After running the code, memory layer (red layer in next image) was obtained as expected:


enter image description here


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...