Created
March 31, 2016 22:16
-
-
Save dcloud/f65686b592de2adfb84ab3ec069c3e4b to your computer and use it in GitHub Desktop.
Quick and dirty KML to shape file conversion, with problems :(
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import ogr | |
import osr | |
import argparse | |
fileEndsWith = '.shp' | |
driverName = 'ESRI Shapefile' | |
def main(): | |
parser = argparse.ArgumentParser(description='Merge KML files into a shapefile (linestrings or points only, for now).') | |
parser.add_argument('files', metavar='N', nargs='+') | |
parser.add_argument('--outfile', required=True) | |
parser.add_argument('--geometry', required=True) | |
args = parser.parse_args() | |
geom_type = None | |
if args.geometry.lower() == 'linestring': | |
geom_type = ogr.wkbLineString | |
elif args.geometry.lower() == 'point': | |
geom_type = ogr.wkbPoint | |
else: | |
raise Exception("Unable to match --geometry argument to a type I can handle") | |
if not args.outfile.endswith('.shp'): | |
raise Exception('outfile must end in .shp') | |
out_driver = ogr.GetDriverByName(driverName) | |
if os.path.exists(args.outfile): | |
out_driver.DeleteDataSource(args.outfile) | |
out_ds = out_driver.CreateDataSource(args.outfile) | |
srs = osr.SpatialReference() | |
srs.ImportFromEPSG(4326) | |
out_layer = out_ds.CreateLayer(args.outfile, srs, geom_type=geom_type) | |
for fname in args.files: | |
if fname.endswith('.kml'): | |
ds = ogr.Open(fname) | |
layer = ds.GetLayer() | |
for feat in layer: | |
geom = feat.geometry() | |
geom.FlattenTo2D() | |
feature_geom_type = geom.GetGeometryType() | |
print(geom.GetGeometryName()) | |
if feature_geom_type == geom_type: | |
out_feat = ogr.Feature(out_layer.GetLayerDefn()) | |
out_feat.SetGeometry(feat.GetGeometryRef().Clone()) | |
out_layer.CreateFeature(out_feat) | |
out_layer.SyncToDisk() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Chould this script is run correctly?