8

In QGIS, I used the Create grid function to produce a grid. It produces an attribute table that looks something like that :

grid attribute table

Now, let say I have a CSV file with the same attributes.

id left top right bottom
"1" -79.765324266 62.582465701 -77.765324266 60.582465701
"2" -79.765324266 60.582465701 -77.765324266 58.582465701
"3" -79.765324266 58.582465701 -77.765324266 56.582465701
"4" -79.765324266 56.582465701 -77.765324266 54.582465701
"5" -79.765324266 54.582465701 -77.765324266 52.582465701

How can I import my CSV in QGIS and recreate the grid based on attributes?

4 Answers 4

12

If you import your CSV as a delimited text layer, you could use the "Geometry by Expression" tool on the layer to construct the polygons with this expression:

make_rectangle_3points(
    make_point("left", "top"),
    make_point("right", "top"),
    make_point("right", "bottom")
)

enter image description here

EPSG:4326

The polygon layer will inherit any attributes from the CSV layer.

2
  • One other alternative, depending on what you prefer, is to add a column to your .csv to generate a WKT "Linestring (left bottom,right top)" and open the .csv with the WKT column as geometry source (this will generate a line grid).
    – Kasper
    Dec 23, 2022 at 15:51
  • 1
    Sounds like a valid answer to me, @Kasper
    – Matt
    Dec 23, 2022 at 15:57
10

A PyQGIS solution.

Proceed with Plugins > Python Console > Show Editor and paste the script below:

# imports
from csv import reader
from ast import literal_eval
from os.path import normpath
from PyQt5.QtCore import QVariant
from qgis.core import edit, QgsProject, QgsField, QgsGeometry, QgsPointXY, QgsFeature, QgsVectorLayer

# a path to the CSV file
path_to_csv = normpath("C:/Users/taras/Python Scripts/grid.csv")

# opening the CSV file as a list
with open(path_to_csv, mode='r') as file:
    reader = reader(file, dialect='excel', delimiter=',')
    list_ = list(reader)
 
raw_data = [] # a holder for raw data
keys_list = list_[0] # only field names
values_list = list_[1:] # only field values 

# function for getting rid of quotes, perhaps quoting=csv.QUOTE_NONE is better to use
def no_quotes(x):
    try:
        return literal_eval(x)
    except:
        return x

# converting each record to its proper data type
values_list_ = [list(map(lambda value: no_quotes(value), values)) for values in values_list]

# zipping a key with a corresponding value
for values in values_list_:
    raw_data.append(dict(zip(keys, values)))

# preparing an empty polygon layer for the output
output_crs = "epsg:4326"
polygon_layer = QgsVectorLayer(f"Polygon?crs={output_crs}", "grid", "memory")

# nesting new fields into the output layer
data_provider = polygon_layer.dataProvider()
data_provider.addAttributes([
    QgsField('id', QVariant.Int),
    QgsField('left', QVariant.Double),
    QgsField('top', QVariant.Double),
    QgsField('right', QVariant.Double),
    QgsField('bottom', QVariant.Double)
    ])
polygon_layer.updateFields()

# editing the polygon layer
with edit(polygon_layer):
    # looping over each record in the raw data
    for record in raw_data:
        # providing fields for each feature
        feat = QgsFeature(polygon_layer.fields())
        # creating four vertices for each polygon feature
        p1 = QgsPointXY(record['left'], record['bottom'])
        p2 = QgsPointXY(record['left'], record['top'])
        p3 = QgsPointXY(record['right'], record['top'])
        p4 = QgsPointXY(record['right'], record['bottom'])
        points = [p1,p2,p3,p4]
        # setting feature's geometry
        geom = QgsGeometry.fromPolygonXY([points]) 
        feat.setGeometry(geom)
        # filling feature with attributes
        feat.setAttributes(list(record.values()))
        # adding feature
        data_provider.addFeatures([feat])
polygon_layer.updateExtents()

# adding polygon layer to the map canvas
QgsProject.instance().addMapLayer(polygon_layer)

Input:

input

Press Run script run script and get the output that will look like this:

result


References:

8

If you can generate additional columns in your .csv you can generate a WKT string (POLYGON) column directly in the .csv:

POLYGON(left bottom, left top, right top, right bottom, left bottom)

and then open the .csv with the WKT column as geometry source.

Note to expand the answer beyond your specific case if you generate a Line grid with QGIS rather than a Place lygon grid.

Then either bottom = top or left = right and you can use LINESTRING type WKT

Linestring (left bottom,right top)
0
6

After importing your CSV, you can use the "Geometry by Expression" tool with the following expressions.

If the grid contains squares, you can use:

make_square(
    make_point("left", "top"),
    make_point("right", "bottom")
)

If not squares, you can also use:

make_polygon( 
    make_line( -- outer ring
       make_point("left", "top"),
       make_point("right", "top"),
       make_point("right" "bottom"),
       make_point("left", "bottom")
    )
)

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.