1

By fetching the top left and bottom right coordinates, I am trying to create a grid over the selected polygon;

import os
import shapefile
import numpy as np

myfilepath = iface.activeLayer().dataProvider().dataSourceUri()

shape = shapefile.Reader(myfilepath, encoding = "ISO8859-1")

feature = shape.shapeRecords()[0]

points = feature.shape.points
points = [list(i) for i in points]

poly_max = np.max(points, axis=0)
poly_min = np.min(points, axis=0)
poly = [poly_max[0], poly_max[1], poly_min[0], poly_min[1]]

Obviously poly prints the coordinates.

The following step is where it goes wrong and I'm not sure why:

processing.run("native:creategrid", {'TYPE':2,'EXTENT':poly+' [EPSG:5845]',
                                     'HSPACING':10,
                                     'VSPACING':14,
                                     'HOVERLAY':0,
                                     'VOVERLAY':0,
                                     'CRS':QgsCoordinateReferenceSystem('EPSG:5845'),
                                     'OUTPUT':'TEMPORARY_OUTPUT'})

I get the following error:

Traceback (most recent call last):
  File "/usr/lib/python3.10/code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "<string>", line 23, in <module>
TypeError: can only concatenate list (not "str") to list

Am I right to conclude that it doesn't approve of using strings in the command? Is there a way to go around this?

3 Answers 3

1

You are creating a list with poly = [poly_max[0], poly_max[1], poly_min[0], poly_min[1]] and you cant concatenate a list with a string like you are doing with poly+' [EPSG:5845]'

Use f strings when combining the variables.

src = r"/home/bera/Desktop/GIStest/12polygons.shp"
vl = QgsVectorLayer(src, "mylayer", "ogr")

#List all features and find the extents 
all_features = [f for f in vl.getFeatures()]

theone = all_features[0] #Select one
bbox = theone.geometry().boundingBox()
xmin, xmax, ymin, ymax = bbox.xMinimum(), bbox.xMaximum(), bbox.yMinimum(), bbox.yMaximum()

#Create the grid.
#The extent parameter for the grid should be a string in this format: xmin,xmax,ymin,ymax [EPSG:XXXX]
    
extent = f"{xmin},{xmax},{ymin},{ymax} [{vl.crs().authid()}]"
grid = processing.run("native:creategrid", 
    {'TYPE':2,'EXTENT':extent,'HSPACING':1000,'VSPACING':1001,
    'HOVERLAY':0,'VOVERLAY':0,'CRS':vl.crs(),'OUTPUT':'TEMPORARY_OUTPUT'})["OUTPUT"]
QgsProject.instance().addMapLayer(grid)

enter image description here

0
0

I sorted it out by replacing 'EXTENT':poly+' [EPSG:5845]', with 'EXTENT':','.join(map(str, poly))+' [EPSG:5845]',.

0

Poly is a list! And ' [EPSG:5845]' is a string. How should a sum of this work?

Just try 'EXTENT': QgsRectangle(xmin, ymin, xmax, ymax).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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