I have a grid from research tools saved as shapefile. I want to display the center coordinate of each grid square in the attribute table.
EDIT: I first thought that your squares were polygons. If they are lines, you need to convert the lines to polygons (vector > geometry tools > Lines to polygon) , then you can apply the method below (for polygons)
In the attribute table, you can compute the X and Y coordinates of the centroid (=the point at the center of the grid square) using the field calculator. The explicit (for X, but of course it also works fo Y) syntax is
but in fact you can use the shortcut
Tested on QGIS 2.18 and QGIS 3.4
I can suggest using a
"Virtual Layer" through
Layer > Add Layer > Add/Edit Virtual Layer...
Let's assume we have a grid as the line features namely
"grid" (sorry if the grid is not that much "grid"), see image below.
With the following Query, it is possible to achieve the result
SELECT MakePoint(ST_X(ST_Centroid(geometry)), ST_Y(ST_Centroid(geometry)), 31469), *, ST_X(ST_Centroid(geometry)) AS X_centr, ST_Y(ST_Centroid(geometry)) AS Y_centr FROM (SELECT MakePolygon(MakeValid(geometry)), * FROM grid)
The output Virtual Layer will be a point layer with following attributes inherited from the initial grid layer.
- Chapter 8. PostGIS Reference | 8.9. Spatial Relationships and Measurements | ST_Centroid
- Chapter 8. PostGIS Reference | 8.4. Geometry Constructors | ST_MakePolygon
- Chapter 8. PostGIS Reference | 8.4. Geometry Constructors | ST_MakePoint
- Chapter 8. PostGIS Reference | 8.11. Geometry Processing | ST_MakeValid
I polygonized the grid, then used centroid.
Strangely lines to polygon did not work, but polygonize did.
We're looking for long answers that provide some explanation and context. Don't just give a one-line answer; explain why your answer is right, ideally with citations. Answers that don't include explanations may be removed.