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?
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.
After running the code, memory layer (red layer in next image) was obtained as expected:
No comments:
Post a Comment