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.
-
3We 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– Michael Stimson2015年03月12日 23:18:57 +00:00Commented Mar 12, 2015 at 23:18
-
1Sorry I didn't clarify. Anything open source, so not arcpy.Scott– Scott2015年03月13日 15:23:46 +00:00Commented Mar 13, 2015 at 15:23
1 Answer 1
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
}
})