Converting WKT to SHP?
An answer to this question on the GIS Stack Exchange.
Question
I have a text file containing exactly this:
POLYGON ((6.2973716 48.98613 1772.1, ...many other Long Lat Altitude values ... ))
And only this. It seems to be just like a WKT geometry of a polygon. But it's only a text file.
I'd like to create an "ESRI Shapefile" from this file, if possible with tools that are available without any installation on Windows.
I've tried GDAL so far but it doesn't seem to handle such files.
Answer
I was able to use GDAL's Python bindings to perform the operation. You can use the following as a command-line script or modify for one-off operation. It will read in WKT strings, one per line, from a file and write them into a shapefile. Be sure to set the projection correctly.
#!/usr/bin/env python3
import csv
import ogr
import os
import osr
import sys
if len(sys.argv)!=3:
print("Syntax: {0} <Input File> <Output File>".format(sys.argv[0]))
sys.exit(-1)
input_file = sys.argv[1]
output_file = sys.argv[2]
layer_name = os.path.splitext(os.path.basename(output_file))[0]
spatialref = osr.SpatialReference() # Set the spatial ref.
spatialref.ImportFromProj4('+proj=aea +lat_1=29.5 +lat_2=45.5 +lat_0=23 +lon_0=-96 +x_0=0 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,-0,-0,-0,0 +units=m +no_defs')
#spatialref.SetWellKnownGeogCS('WGS84') # WGS84 aka ESPG:4326
driver = ogr.GetDriverByName("ESRI Shapefile")
dstfile = driver.CreateDataSource(output_file) # Your output file
# Please note that it will fail if a file with the same name already exists
dstlayer = dstfile.CreateLayer(layer_name, spatialref, geom_type=ogr.wkbMultiPolygon)
# Add the other attribute fields needed with the following schema :
fielddef = ogr.FieldDefn("ID", ogr.OFTInteger)
fielddef.SetWidth(10)
dstlayer.CreateField(fielddef)
# Read the feature in your csv file:
with open(input_file) as fin:
for nb, row in enumerate(fin.readlines()):
# WKT is in the second field in my test file :
poly = ogr.CreateGeometryFromWkt(row)
feature = ogr.Feature(dstlayer.GetLayerDefn())
feature.SetGeometry(poly)
feature.SetField("ID", nb) # A field with an unique id.
dstlayer.CreateFeature(feature)
feature.Destroy()
dstfile.Destroy()