3

in QGIS there's a very useful tool "Select features by radius", I'd like to add a similar function in my plugin. The user should be able to choose the radius and the center of the circle (from a chosen feature).

Is there a way to call "Select features by radius" using PyQGIS?

I can't find anything useful.

2 Answers 2

2

Thanks to artwork21 and Ben W advices, I've written this code. Probably there's a better way to do the same thing, but it seems to work.

#userFeature is user input
#userDistance is user input

layer = QgsProject.instance().mapLayersByName('myLayer')[0]
it = layer.getFeatures( QgsFeatureRequest( QgsExpression("id = '"+userFeature+"'") ) )
ids = [i.id() for i in it]
layer.selectByIds(ids) 

selection = layer.selectedFeatures()
for feat in selection:
    geom = feat.geometry()
    buff = geom.buffer(userDistance,5)

intersectedFeaturesList=[]

for feature in layer.getFeatures():
    if feature.geometry().intersects(buff):
        intersectedFeaturesList.append(str(feature.attributes()[0])) #attributes()[0] are the ids in my layer

seperator = ', '
rowsString=seperator.join(intersectedFeaturesList)
expr = QgsExpression( "id in ("+rowsString+")")

it=layer.getFeatures(QgsFeatureRequest(expr))
ids = [i.id() for i in it]
layer.selectByIds(ids)
1

Not sure about the select feature by radius method but you could create a plugin where the user defines a selection point on the map which then in the back-end creates an in-memory buffered polygon (by x distance, distance sourced from a textbox widget in a Qt form) which selects any feature(s) that intersect the buffer layer.

3
  • It's a good idea, I'll try in this way. Thanks
    – Lorenzo
    Dec 2, 2019 at 21:47
  • Hi spent my all afternoon looking for buffer usins PyQGIS. I didn't find versions compatible with qgis 3. Do you have any idea?
    – Lorenzo
    Dec 3, 2019 at 17:28
  • @Lorenzo, buffer() is a method of the QgsGeometry class. See the docs here: qgis.org/api/….
    – Ben W
    Dec 3, 2019 at 22:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.