# Create a center line for each polygon

I am trying to create a line in the center of each polygon of my shape like the red lines in the picture below (all polygons are rectangles). There's almost 22.000 polygons and I can't figure out how to do this. Any idea ? • Yes @snaileater always rectangles. Jun 10, 2020 at 15:25

If all polygons are rectangles, i guess you are looking for the average of the long sides.

In this case, if it is a one time task, this should do the trick:

1. start at point 0 of the border and check if distance from 0 to 1 is lower than distance from 0 to 3.

2. case true: get coordinates of midpoint of sides 0-1 and 2-3.

3. case false: get cooridnates of midpoint of sides 2-3 and 0-3.

4. Build new line geometry using the just fount midpoints

In QGIS:

Use the field calculator to get the coordinates:

build 4 columns:

X1:

``````if((\$x_at(0)-\$x_at(1))^2+(\$y_at(0)-\$y_at(1))^2 < (\$x_at(0)-\$x_at(3))^2+(\$y_at(0)-\$y_at(3))^2,\$x_at(0)/2+\$x_at(1)/2,\$x_at(0)/2+\$x_at(3)/2)
``````

Y1:

``````if((\$x_at(0)-\$x_at(1))^2+(\$y_at(0)-\$y_at(1))^2 < (\$x_at(0)-\$x_at(3))^2+(\$y_at(0)-\$y_at(3))^2,\$y_at(0)/2+\$y_at(1)/2,\$y_at(0)/2+\$y_at(3)/2)
``````

X2:

``````if((\$x_at(0)-\$x_at(1))^2+(\$y_at(0)-\$y_at(1))^2 < (\$x_at(0)-\$x_at(3))^2+(\$y_at(0)-\$y_at(3))^2,\$x_at(2)/2+\$x_at(3)/2,\$x_at(1)/2+\$x_at(2)/2)
``````

Y2:

``````if((\$x_at(0)-\$x_at(1))^2+(\$y_at(0)-\$y_at(1))^2 < (\$x_at(0)-\$x_at(3))^2+(\$y_at(0)-\$y_at(3))^2,\$y_at(2)/2+\$y_at(3)/2,\$y_at(1)/2+\$y_at(2)/2)
``````

Then build the geometry column

wkt_geometry:

``````concat('LINESTRING( ',"X1",' ',"Y1",',',"X2",' ',"Y2",')')
``````

Then, export layer as csv, and reload it with the csv driver, set wkt_geometry as the geometry field.

• Please edit the question adding the new info. Jun 10, 2020 at 15:21
• it's worked, but partially...some lines had a weird behavior, didn't get parallels. But now I understand. On some rectangles there are vertex dividing the longer side of polygon. Jun 10, 2020 at 15:32
• Ok, if this fits your needs, please edit the question to add that info, i.e: all polygons are rectangles. And accept the answer. Did you try simplify geometries in order to drop the extra mid-side vertexes? Jun 10, 2020 at 15:38
• I used simplify now and it worked very well...thank you very much. Jun 10, 2020 at 17:49