1

What is the fastest way to save MultiLineString to Shapefile (without attributes) and KML/KMZ? Preferred open-source libraries like fiona, shapely etc.

from osgeo import ogr

multiline = ogr.Geometry(ogr.wkbMultiLineString)

for (X1, Y1, X2, Y2) in coordinates:
    line = ogr.Geometry(ogr.wkbLineString)
    line.AddPoint(X1, Y1)
    line.AddPoint(X2, Y2)
    multiline.AddGeometry(line1)

When I print the multiline on the console:

print(multiline.ExportToWkt())

I get something like this:

MULTILINESTRING ((10.0 15.0 0,10.5 15.5 0),(20.0 25.0 0,20.5 25.5 0))

I would like to save these two lines to Shapefile and KML/KMZ as two separate lines.

1 Answer 1

1

For shapefiles, you can use following code:

from osgeo import ogr
import fiona
from fiona.crs import from_epsg
from shapely.geometry import mapping
from shapely.wkt import loads

crs = from_epsg(32612)

multiline = ogr.Geometry(ogr.wkbMultiLineString)

coordinates = [(354978.589749, 4473420.68314, 354988.874487, 4473425.9451)]

for (X1, Y1, X2, Y2) in coordinates:
    line = ogr.Geometry(ogr.wkbLineString)
    line.AddPoint(X1, Y1)
    line.AddPoint(X2, Y2)
    multiline.AddGeometry(line)

lines = [ loads(multiline.ExportToWkt()) ]

#creation of the resulting shapefile
schema2 = {'geometry': 'MultiLineString','properties': {'id': 'int'},}

with fiona.open('/home/zeito/pyqgis_data/new_multilinestring.shp', 'w', 'ESRI Shapefile', schema2, crs)  as output:
    for i, line in enumerate(lines):
        output.write({'geometry':mapping(line),'properties': {'id':i}})

For kml/kmz, I cannot see any drivers:

>>> import fiona
>>> fiona.supported_drivers
{'ESRI Shapefile': 'raw', 'ARCGEN': 'r', 'PCIDSK': 'r', 'SUA': 'r', 
'DGN': 'raw', 'SEGY': 'r', 'MapInfo File': 'raw', 'GeoJSON': 'rw', 'PDS': 'r', 
'FileGDB': 'raw', 'GPX': 'raw', 'DXF': 'raw', 'GMT': 'raw', 'Idrisi': 'r', 
'GPKG': 'rw', 'OpenFileGDB': 'r', 'BNA': 'raw', 'AeronavFAA': 'r', 
'GPSTrackMaker': 'raw'}
0

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