I am new to Python and I am using the Python console in QGIS 3.10 to make the coordinate grid on a vector layer. I had lots of vector files which are basically square shaped of 500 meters but all are of different location. I want to export this vector file but after making grid on top of that. I want to do it in Python as I can loop it and do all the process at once. My workflows goes like this:

  • Load vector layer
  • Open map canvas
  • Display vector layer in map canvas
  • Make coordinate grid on top of that
  • Export that as image

The sample image of what i want is like this: Initial Vector layer: enter image description here

After making Grids on that enter image description here

Here is my code and in output it is nit creating the grids `

fn = r"C:\Users\Asus\OneDrive\Documents\map secien\360m\parent grid\grid_no_A1.shp"
layer = iface.addVectorLayer(fn, 'grid_no_A1', 'ogr')

from qgis.PyQt import QtGui
layers = QgsProject.instance().mapLayersByName('grid_no_A1')
layer = layers[0] 
project = QgsProject.instance()
manager = project.layoutManager()
layoutName = 'Layout1'
layouts_list = manager.printLayouts()

# remove any duplicate layouts
for layout in layouts_list:
    if layout.name() == layoutName:

layout = QgsPrintLayout(project)

# create map item in the layout
map = QgsLayoutItemMap(layout)
map.setRect(20, 20, 20, 20)

# set the map extent
ms = QgsMapSettings()

# set layers to be mapped
rect = QgsRectangle(ms.fullExtent())
map.setBackgroundColor(QColor(255, 255, 255, 0))
map.attemptMove(QgsLayoutPoint(5, 20, QgsUnitTypes.LayoutMillimeters))
map.attemptResize(QgsLayoutSize(180, 180, QgsUnitTypes.LayoutMillimeters))

grid = QgsLayoutItemMapGrid(layout)
out = QgsLayoutItemMap(layout)
grid = QgsLayoutItemMapGrid("hr", out)

layout = manager.layoutByName(layoutName)
exporter = QgsLayoutExporter(layout)
fn = r'C:\Users\Asus\OneDrive\Documents\map secien\layout_export.jpeg'
exporter.exportToImage(fn, QgsLayoutExporter.ImageExportSettings())
  • 2
    Coding questions here are expected to contain code. We'll help you with specific errors, but we don't want to become a coding service. – Vince Sep 5 at 14:54

Your Answer

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

Browse other questions tagged or ask your own question.