I found this code snippet in Selecting features within certain buffer distance of selected feature using PyQGIS?, which is almost what I'm looking for, except I don't have polylines but points and I want to find another layers points in radius.
I tried to edit the code above, but I'm confused when to switch layers and how to select the points in radius properly, so that I can call my "do something"-function.
Here my code so far:
def selectPointsInRadius(bufDist):
inputlayer = QgsMapLayerRegistry.instance().mapLayersByName('points')[0]
print ('points-layer found')
#stores features in a dictionary for fast access
featDict = {feature.id(): feature for (feature) in inputlayer.getFeatures()}
#spatial index for faster spatial queries
featIdx = QgsSpatialIndex(inputlayer.getFeatures())
try:
itlayer = QgsMapLayerRegistry.instance().mapLayersByName('itpoint')[0]
print ('itpoint-layer found')
itlayer.selectAll()
for point in itlayer.selectedFeatures():
xyList = point.geometry().asPoint()
print(xyList)
minx = min([xy[0] for xy in xyList]) #minimum x-coordinate
maxx = max([xy[0] for xy in xyList]) #maximum x-coordinate
miny = min([xy[1] for xy in xyList]) #minimum y-coordinate
maxy = max([xy[1] for xy in xyList]) #maximum y-coordinate
ids = featIdx.intersects(QgsRectangle(minx - bufDist, miny - bufDist, maxx + bufDist, maxy + bufDist))
#lyr.selectByIds(ids) #use this if you don't need total accuracy, much faster!!
tids = [] #true ids of nearby features that we want to select
for id in ids:
if featDict[id].geometry().distance(line.geometry()) < bufDist:
print ("found features in radius")
tids.append(id)
print ("selected features in radius")
lyr.selectByIds(tids, 1) #add to selection,
#call doSomething-function here?
except IndexError:
print ('itpoint does not exist')
processing.runalg("qgis:selectbylocation", inputlayer, itlayer, u'within', bufDist, 0)
import processing
, then define your layers as you have done in your script (i.e.inputlayer = QgsMapLayerRegistry.instance().mapLayersByName('points')[0]
). Then just run the commandprocessing.runalg("qgis:selectbylocation", inputlayer, itlayer, u'within', 50, 0)
to create a bounding box precision of 50 units. It might not be what you're looking for as it doesn't create a search buffer, only a bounding box.