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.

nmtoken
13.6k5 gold badges39 silver badges91 bronze badges
asked Mar 12, 2015 at 21:09
2
  • 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. Commented Mar 12, 2015 at 23:18
  • 1
    Sorry I didn't clarify. Anything open source, so not arcpy. Commented Mar 13, 2015 at 15:23

1 Answer 1

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
 }
 })
answered Mar 17, 2015 at 1:41

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.