In the following PyQGIS script, I iterate through each shapefile in input_directory, where each file represents an individual prefecture. To manage project isolation and ensure clean operations, I create a new instance of QgsProject (project = QgsProject.instance()
) at the beginning of each iteration.
Within each loop iteration, layers are added to the project: an OpenStreetMap layer (rlayer), a prefectures layer (prefectures), and the individual prefecture layer (individual_prefecture). After adding layers to the project, I save the project to a specified directory with a unique filename based on the prefecture's name (project.write(path_project)
). Finally, I clear the project instance (project.clear()
) to release resources before moving to the next iteration. The number of projects created are equal to the number of prefectures.
The problem is that the layers are not at the right location (see below image). This screendhot is based on one QGIS project file. The same applies for all QGIS projects created. The black region shows where the layers should be located.
wrong position of the layers added to the project
The weird thing is that if I exclude the following line project.clear()
the positions of the layers are right but there are more layers than I want (see 2nd image). The QGIS project includes the shapefiles of more than one prefecture. As for QGIS project named QGIS_Project_prefecture_3_2100
I would expect only the three first layers. project.removeAllMapLayers
did not solve my problem either.
example removing project.clear()
I have attached my code below:
from qgis.core import QgsProject, QgsLayout, QgsLayoutItemMap
from qgis.gui import QgisInterface
import os
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QGraphicsPixmapItem
print(os.getcwd())
input_directory = "F:\Tutorials\Layout_plot_qgis\individual_prefectures_2100"
qgis_project_directory = "F:\Tutorials\Layout_plot_qgis\projects_qgis"
# Loop through each shapefile in the directory
for filename in os.listdir(input_directory):
if filename.endswith(".shp"):
# Construct the full path to the shapefile
filepath = os.path.join(input_directory, filename)
filename_without_extension = os.path.splitext(os.path.basename(filename))[0]
print(filename_without_extension)
# project code
project_name = f"QGIS_Project_{filename_without_extension}.qgz"
path_project = os.path.join(qgis_project_directory, project_name)
project = QgsProject.instance()
project.setTitle(project_name)
urlWithParams = 'type=xyz&url=https://tile.openstreetmap.org/{z}/{x}/{y}.png&zmax=19&zmin=0&crs=EPSG3857'
rlayer = QgsRasterLayer(urlWithParams, 'OpenStreetMap', 'wms')
print(rlayer.crs())
if rlayer.isValid():
project.addMapLayer(rlayer)
else:
print('invalid layer')
print(rlayer.error().summary())
# # adding perifereies
path_shp = "F:\Tutorials\Layout_plot_qgis\periphereies (1)\periphereies\periphereies.shp"
prefectures = QgsVectorLayer(path_shp, 'prefectures', 'ogr')
if not prefectures.isValid():
print("Layer failed to load!")
else:
QgsProject.instance().addMapLayer(prefectures)
# print(prefectures.id)
#######
## Adding individual prefecture
#######
individual_prefecture = QgsVectorLayer(filepath,str(filename_without_extension), 'ogr')
if not individual_prefecture.isValid():
print("Layer failed to load!")
else:
QgsProject.instance().addMapLayer(individual_prefecture)
print(individual_prefecture.id)
project.write(path_project)
project.clear()
-
1It looks like a CRS problem. Maybe you are loading your .shp layers without .prj files and in your new project (after project.clear()) they are loaded in project CRS which is different than those layer's CRS? .shp files without .prj files are loaded by default in project CRS which is set in the original project but clearing project also clears CRS settings.rychlik– rychlik2024年07月10日 22:07:57 +00:00Commented Jul 10, 2024 at 22:07
-
All the shapefiles I added have the same projection (epsg:2100) except openstreetmap of course.Ilias Machairas– Ilias Machairas2024年07月11日 06:43:16 +00:00Commented Jul 11, 2024 at 6:43
-
I meant that if you add first layer to the project then the project automatically gets this layer's CRS set up as a project CRS. If all the shapefiles you want to add do have .prj files then maybe try to switch the order of adding layers (first shp then osm) and then change layer order in the layers list if it's important or add the same way as you do now but include a new step to change project CRS to EPSG:2100.rychlik– rychlik2024年07月12日 06:54:26 +00:00Commented Jul 12, 2024 at 6:54
1 Answer 1
I fixed the problem by adding project.setCrs(QgsCoordinateReferenceSystem(2100))
. The code is presented below:
[...]
project.setCrs(QgsCoordinateReferenceSystem(2100))
project.write(path_project)
project.clear()
[...]
@rychlik is right, and the CRS settings were deleted when project.clear()
was executed.