Geographic Information Systems Asked on May 22, 2021
Is it possible to get the direction of the longest side of a rectangle in QGIS?
I know how to get the direction of a line layer. But I need to know the direction of a polygon. One could start at the center of a polygon and find the shortest way to the border by using a line and take the direction of this line, but I don’t know how to draw this line automatically for 30000 polygons.
I have a way which might work just using QGIS vector operations and expressions. It finds the angle of the longest segment of polygon features.
In outline:
angle
attribute to the remaining simple line segments using the atan2
function.Now your polygon has a joined "angle" attribute which is the angle of the longest side (in radians).
That's the algorithm. The implementation follows:
You'll need "Polygons to lines" from the QGIS toolbox and then "Explode lines" from the toolbox for the first two steps.
To get the longest simple line segments grouped by "id" variable, do "Select by expression" and use: $length != maximum($length, "id")
- your id
variable might have another name, it needs to be unique per polygon. Apply that and you should have most of the simple line segments selected. Turn on editing for that layer and cut those features.
Create the angle column by adding a new attribute called "angle", and updating it with the following formula:
atan2(y_max($geometry) - y_min($geometry),x_max($geometry)-x_min($geometry))
Then switch editing off for that exploded layer and save.
Finally, use the polygon layer properties to create a Join from the polygons to the line segments, matching on the id
attribute.
Look now at the attribute table of your polygons, and it should have the angle of the longest line segment from the joined line segment layer.
Note this is not dynamic so if you change the polygons it will not update properly, you'll have to start again. I suspect this workflow could be wrapped into a flow diagram....
Answered by Spacedman on May 22, 2021
If you run the "Oriented Minimum Bounding Box" algorithm over your layer, you'll get a new angle field in your layer which indicates the angle of this minimum bounding box. I suspect that's what you require.
Answered by ndawson on May 22, 2021
In QGIS 3.16+ there is a new function: main_angle()
that makes things easier.
Answered by Francesco Catani on May 22, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP