[GIS] How to turn all lines into one direction

linepostgispythonqgis

How can I turn all features of my polyline (postgis and/or shapefile) into one direction – it doesn't matter what direction. I know how to switch the direction of lines but I have no idea how to bring all lines (I have thousands of them) into one single direction.

enter image description here

EDIT:

A line can have only two directions, the one or the other like 0 or 1. I want them all to have the direction 0 OR 1. For example the left line in the image is in direction 1 the middle line is in direction 0 and the right one is in direction 1. Now I want the middle line to direction 1 OR the right and left line to direction 0. So that all lines have the same direction 1 OR 0.

geom;given_direction;wanted_direction
line;1;1
line;0;1
line;1;1
line;1;1
line;0;1
line;1;1

Best Answer

I assume with "one direction" you mean that every segment of a collection of polylines should show into one direction. Also there is a need, that the segments in the collection are in the right order following a single path.

Given this, things are easy: You are searching for pretty much the same thing, I did a couple of months ago. The StackOverflow Community helped me out with this... look here.

Things are getting harder if you have to collect the connected polylines first: A possible algorithm could be:

  1. Take first polyline A.
  2. Save Start Point in a variable
  3. Save End Point in a variable
  4. Take next polyline B
  5. compare A.endPoint with B.startPoint: if equals then merge A and B to A and start over with 3.
  6. comapre A.startPoint with B.endPoint: if equals then merge B and A to A and start over with 2.
  7. compare A.endPoint with B.endPoint: if equals then merge A and B.reverse() to A and start over with 3.
  8. compare A.startPoint with B.startPoint: if equals then merge B.reverse() and A to A and start over with 2.
  9. Do this until no unordered polylines are left.

In this algorithm it doesn't matter if you merge all Coordinates into one big linestring, or into a 2 dimensional sorted array which is in fact a multilinestring.

Related Question