I have a spatial table in SQL Server with point features, and connected it to QGIS which neatly shows all points.

Now I want to select points in this table (and show them in the map) within a certain radius from a certain point.

I am building a plugin in QGIS to perform this, based on a postal code api (which gives a point) and a radius.

My question is: how to select these points with Python? With the setSubsetString command? If yes, what should be the filtering criterion string, and if not, how then?


I have already working code to request the postal code api, and centre the map on the resulting point (lon, lat).

The code for the postal code point is:

map_pos = QgsPointXY(lon, lat)

The code for the layer to be queried / filtered is:

pr = QgsProject.instance().mapLayersByName('Project')[0]

The points in this layer are in the geography type field 'Position'.

Then I want to use pr.setSubsetString( 'filterstring') to select the points in this layer that are within a radius of say 1 km around point map_pos.

Which 'filterstring' should I use?


Im not sure about the measurements (coordinate system in degrees, distance in meters) but the results doesnt look unreasonable:

layer = iface.activeLayer()

distance = QgsDistanceArea()

search_distance = 50000 #m
map_pos = QgsPointXY(14.4602,57.5751)

to_select = []

for point in layer.getFeatures():
    p = point.geometry()
    if distance.measureLine(p.asPoint(), map_pos) <= search_distance:

layer.select(to_select) #If you want to select
#layer.setSubsetString('id IN{}'.format(tuple(to_select))) #Or filter

enter image description here

But there must be a MSSQL equivalent of something like postgis ST_DWithin which must be alot faster than above code?

| improve this answer | |
  • For instance SELECT * FROM Project WHERE Position.STDistance(GEOMETRY::Point(10, 30, 4326)) <= 0.5. My former post that was not answered tried to get a clue how to use such a query in Pyqgis. – SWP_IB May 7 at 12:22
  • Then maybe you can use Execute SQL and pass output ids to pyqgis select – BERA May 7 at 12:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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