I have looked at your data and the book example, the problem is that there are three invalid polygons in data that are processed in the book:
GSHHS_l_L1.shp
ID = 92-W
POLYGON ((-180.0 71.514793999999995,-179.69008299999999 71.577888999999999,-178.648889 71.577416999999997,-178.40644399999999 71.549916999999994,-177.406306 71.244167000000004,-177.877444 71.022889000000006,-179.500111 70.863749999999996,-179.93011100000001 70.979583000000005,-180.0 70.962072000000006))
ID = 486-W
POLYGON ((-180.0 -16.799126,-179.84419399999999 -16.691278,-179.80041700000001 -16.789193999999998,-179.850472 -16.878361000000002,-180.0 -16.959561))
GSHHS_l_L2.shp
ID = 7333-W
POLYGON ((-180.0 65.393473,-179.76583299999999 65.428332999999995,-179.95416700000001 65.385555999999994,-179.90972199999999 65.316389,-180.0 65.321635))
Because this is an example it would be easiest to delete those polygons from the dataset or just add one if statement in you code
if geometry.IsValid():
cursor.execute("INSERT INTO gshhs (level, geom) VALUES (%s, ST_GeomFromText(%s, 4326))", (level, wkt))
You are almost there. You just need to call the ExportToWkb
function.
import ogr
# Get the driver
driver = ogr.GetDriverByName('ESRI Shapefile')
# Open a shapefile
shapefileName = "D:/temp/myshapefile.shp"
dataset = driver.Open(shapefileName, 0)
layer = dataset.GetLayer()
for index in xrange(layer.GetFeatureCount()):
feature = layer.GetFeature(index)
wkb = feature.GetGeometryRef().ExportToWkb()
Best Answer
Internally, PostGIS stores geometries in a binary specification, but it is queried and viewed outside as a hex-encoded string. There are two popular variations of well-known binary (WKB):
ST_AsEWKB
) - an extended WKB specification designed by PostGIS.ST_AsBinary
) - specified by the OGC and ISO. For a while it was 2D-only, but later extended to supportZ
,M
andZM
geometries.The two specifications are the same for 2D geometries, but are different for higher-order geometries with
Z
,M
andZM
coordinates.Older versions of GDAL/OGR (1.x) only understand the EWKB for 3D geometries, so for these I recommend using
ST_AsEWKB
. (But if you only have 2D geometries, either format are fine). For example:Also, note that older GDAL/OGR versions do not support
M
coordinates, and these will be parsed but ignored.With GDAL 2.0 and more recent, ISO WKT/WKB is supported. This means that
CreateGeometryFromWkb
can read either WKB flavour (without specifying) andExportToIsoWkt()
shows output with a modern WKT syntax.Additionally, GDAL 2.1 or later will create/export WKT/WKB with
M
orZM
coordinates as expected.