[Qgis-user] Python code to select polygon at location

Zoltan Szecsei zoltans at geograph.co.za
Sun Aug 25 06:19:34 PDT 2024


Hi,
I'm doing my "once a year need to do something in python with QGIS" :-/
Using QGIS 3.38 and PyCharm.

I have a SHP file with 28000 polygons.
Another SHP file with 22000 Points
Both in EPSG:4326

Without using QGIS processing, what is the quickest way to, for each 
point 1 by 1, find the underlying polygon and read the attribute field 
values of that polygon?
The code snippet below is far too inefficient - but I cannot find code 
that selects at XY and benefits from any spatial index on the polygons.

    	lyr_poly = QgsVectorLayer(polygon_shp, '', 'Ogr')       point =
    QgsPointXY(lon, lat)       request =
    QgsFeatureRequest().setFilterRect(lyr_poly.extent())       for
    feature in lyr_poly.getFeatures(request):           geom =
    feature.geometry()           if
    geom.contains(QgsGeometry.fromPointXY(point)):           
    lyr_poly.select(feature.id())               print(f"Feature with ID
    {feature.id()} is selected.")               break

Thanks in advance,
Zoltan

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-user/attachments/20240825/f191c32f/attachment.htm>


More information about the QGIS-User mailing list