Python – Merging Multiple Overlapping Lines

lineoverlapping-featurespython

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.

Best Answer

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
        }
    })