Search code examples
javascriptmapsgeojsonturfjs

reorder LineString coordinates GeoJson


I have a large set of GeoJson data made up of many LineStrings. I need to reorder the coordinates of all the LineStrings so that there's as little zig-zag as possible. so for example i have this set of coordinates:

[
      [
        -149.858345,
        61.217461,
        0
      ],
      [
        -151.544282,
        59.646368,
        0
      ],
      [
        -124.099861,
        43.982118,
        0
      ],
      [
        -151.291694,
        60.689824,
        0
      ]
]

which results in this line

enter image description here

where instead it should be reordered like this

[
     [
        -149.858345,
        61.217461,
        0
      ],
      [
        -151.291694,
        60.689824,
        0
      ],
      [
        -151.544282,
        59.646368,
        0
      ],
      [
        -124.099861,
        43.982118,
        0
      ]
]

which renders this

enter image description here

which is a much more sensible line.

I realize "sensible" is subjective here, another way to look at it, is how do I reorder the coordinates so I get the straightest line?

Is this something I might use turf.js for? i looked through the documentation but couldn't find an appropriate function ( or maybe I'm thinking about it the wrong way )

thanks in advance!


Solution

  • There's nothing built-in with Turf for this, and this tends to be one of those problems that has common-sense solutions if you're a person but is hard to define to a computer. That said, how I'd solve this is:

    Another way to do it would be:

    • Use turf-concave or concaveman to generate a concave hull around the points
    • Iterate through the segments of the hull, identify the longest one, and remove it, to make the polygon into a LineString.