Tuesday, 1 January 2019

shapefile - Join line segments sharing a common attribute, using GDAL


I'm having trouble rendering a shapefile consisting of trail routes broken down into many short segments. So I'd like to combine them into a small number of line features, which share a NAME and touch each other.


Is this possible using GDAL? Failing that, are there other tools that don't require scripting? (I see this Python script could probably be adapted but I'd prefer a more general solution if available...)




Answer



It is probably possible with GDAL but not extremely easy. Everything that can be done with SQL in SpatiaLite can also be done with GDAL http://www.gdal.org/ogr_sql_sqlite.html and this query could be used as starting point:


ogrinfo -dialect sqlite test.shp -sql "select attr, st_union(geometry) from test group by attr"

However, the query creates one MultiLineString for each value of "attr" even if it has distinct parts and more complicated SQL would be required.


Instead of finding the SQL solution you may consider using OpenJUMP


This is what you have in the beginning


enter image description here


Find the "Dissolve" tool


enter image description here



Select field(s) that you want to use for dissolving. "Merge linestrings" combines connected lines which is good for you.


enter image description here


However, line "a" is still a two-part MultiLineString


enter image description here


Next you can select all MultiLineStrings from the whole layer with Edit - Selection - Select by Geometry Type [MultiLineString] and press the right button of the mouse for selecting "Explode Selected Features" and the result should please you.


enter image description here


The same can probably be done also with QGIS by starting with algorithm QGIS geoalgorithmns - Vector geometry tools - Dissolve but as I tried it I did not find a way for combining the connected "a" segments into a single linestring element.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...