Firstly, your layers are shown in the correct location on the map canvas because QGIS re-projects layers on the fly to the project CRS for visualization.
Secondly, you have not said how you "converted" the CRS of your layers but, if you right clicked on the layer in the Table of Contents and used 'Set Layer CRS' option, that is not the way to change layer CRS. If you did that you should set them back to their correct CRS before doing anything else. To re-project a layer you can either save/export the layer and choose a different target CRS or use the Reproject Layer algorithm from the Processing Toolbox.
Solution:
Since your question is about PyQGIS
, you can easily work with layers in different coordinate reference systems in the code without having to reproject layers. To do this, you can simply transform one of the QgsGeometry
objects you are working with to match the CRS of the other, using the QgsCoordinateTransform
class, passing a source CRS, destination CRS and QgsProject
instance to the class constructor. Then call transform()
on whichever geometry is in the source CRS.
Like this:
poly = QgsProject.instance().mapLayersByName('polygons')[0]
pnt = QgsProject.instance().mapLayersByName('points')[0]
geom_poly = poly.selectedFeatures()[0].geometry()
geom_pnt = pnt.selectedFeatures()[0].geometry()
# Create a QgsCoordinateTransform object, passing source CRS, dest CRS & QgsProject
xform = QgsCoordinateTransform(pnt.crs(), poly.crs(), QgsProject.instance())
# transform pnt_geom to poly_geom CRS (pass QgsCoordinateTransform object to the transform() call
geom_pnt.transform(xform)
# now should print True
print(geom_pnt.intersects(geom_poly))
See the relevant parts of documentation for QgsCoordinateTransform
and QgsGeometry
classes:
https://api.qgis.org/api/classQgsCoordinateTransform.html#aefa41b71beec7d5e46dfd4d04655fc4a
https://api.qgis.org/api/classQgsGeometry.html#a45a9753a80833dfb65f05b93ed019a57
And if you want to loop through all features in both layers to find the points which intersect with each polygon, you can use this approach. This should be fast and efficient since we are using a QgsSpatialIndex
.
poly = QgsProject.instance().mapLayersByName('polygons')[0]
pnt = QgsProject.instance().mapLayersByName('points')[0]
idx = QgsSpatialIndex(pnt.getFeatures())
# Create a QgsCoordinateTransform object, passing source CRS, dest CRS & QgsProject
xform = QgsCoordinateTransform(poly.crs(), pnt.crs(), QgsProject.instance())
for f in poly.getFeatures():
geom_poly = f.geometry()
geom_poly.transform(xform)
bb = geom_poly.boundingBox()
for ft in pnt.getFeatures(idx.intersects(bb)):
if ft.geometry().intersects(geom_poly):
#do something...