2

I have a shapefile with different line features, some of which overlap. Is there a way to easily merge all overlapping lines into one, new feature using Python?

I've seen some solutions for overlapping polygons, but have had a lot more trouble finding examples using lines.

  • 3
    We would really need to know what python? is it arcpy, pyqgis, other? The most of the work would be done using the underlying spatial software so it's important to know what the options are. Please edit your question and put in appropriate software tags, if you have ArcGis and QGIS include both but please indicate the license level for ArcGis as some of the better tools aren't available on basic and standard licenses. – Michael Stimson Mar 12 '15 at 23:18
  • 1
    Sorry I didn't clarify. Anything open source, so not arcpy. – Scott Mar 13 '15 at 15:23
6

In Python using the fiona library to read the file and shapely to do the geometry operations it's easy to merge the geometries. For example:

import fiona
import shapely.geometry
import shapely.ops

with fiona.open(path) as src:
    merged_geometries = shapely.ops.linemerge([
        shapely.geometry.shape(feature["geometry"]) for feature in src])

The merged geometry will either be a LineString or a MultiLineString depending on whether a single contiguous line can be formed or not.

You can then write the result back out to a shapefile using fiona (see the docs on writing files), or really do whatever you like with it.

with fiona.open(path) as src:
    crs = src.crs
    driver = src.driver

schema = {
    "geometry": merged_geometries.geom_type,
    "properties": {
        "length": "float"
    }
}

with fiona.open(out_path, "w", driver=driver, crs=crs, schema=schema) as dest:
    dest.write({
        "geometry": shapely.geometry.mapping(merged_geometries),
        "id":"-1",
        "properties": {
            "length": merged_geometries.length
        }
    })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.