# Obtaining coordinates from center of grid squares (research tools)

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.

• Just use add geometry attributes under vector->geometry tools. – Erik Apr 25 at 13:35
• @Erik with polygons, add geometry attribute will add the area and the perimeter, but not the centroids X and Y – radouxju Apr 25 at 14:00

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

x(centroid(\$geometry))

but in fact you can use the shortcut

x(\$geometry)

• This seemed to give me the center point for each line in the grid, rather than the center of each grid square. – Martin Alberter Apr 25 at 18:33
• If you have a grid of lines, but want to know the center of each 'cell' of a grid, you must first convert your grid of lines into a polygon. – Mox Apr 25 at 23:17
• If your grid is regular, you can may be just add manually half the width of the grid : x(\$geometry) + (Width/2) – Christophe Apr 26 at 7:45
• @Christophe good idea if the grid is regular and the lines are parallel with the x/y axes, but this might also require some clean up first: split lines at each intersection and select only the vertical lines – radouxju Apr 26 at 7:50

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.

References:

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.