Thursday 28 December 2017

How to convert a shapefile to WKT?


I'm trying to convert a shapefile into the simple Well Known Text (WKT) format in the example below (from http://en.wikipedia.org/wiki/Well-known_text).



MULTIPOLYGON (((40 40, 20 45, 45 30, 40 40)),
((20 35, 45 20, 30 5, 10 10, 10 30, 20 35),
(30 20, 20 25, 20 15, 30 20)))

I know that I use QGIS to save the shapefile as a CSV, and I can use ogr2ogr to do any numer of conversions. In fact ogr2ogr -f CSV out.wkt source.shp -lco GEOMETRY=AS_WKT gets me as close as I've come so far, but not quite there. Any suggestions?


p.s. As noted by Mapperz, this thread is very similar to this one. That thread, while it provided the ogr2ogr approach that I noted above, did not solve this particular challenge. The ogr2ogr output I'm getting looks like this (I've truncated the lines). Apparently, I just haven't figured out how to get ogr2ogr to use multipolygon.


WKT,AREA,PERIMETER,PINUPOND_,PINUPOND_I,CODE
"POLYGON ((-120.630531650950061 50.838562484449184, . . .
"POLYGON ((-123.206067372148397 51.038984074378327, . . .

Answer




Well Known Text is not meant for saving layers like shape files that consists of many objects. WKT defines how to represent geometry of one object. That geometry could be single or multi part. Multi part geometries mean that geometry of one object consists of many parts. For example Hawaiian Islands could be represented as one object but it consists of many geometries.


Shape file is a collection of these kinds of objects. Objects usually have also some attribute information that is also part of a shape file.


Your ogr2ogr approach converts these objects to csv format with WKT geometry (and text representations of the attributes). If you really want to combine all the geometries to one MULTIPOLYGON you have to first convert all the objects to one multi geometry. You can do that in QGIS. Select from Vector menu Geometry Tools and then Singleparts to Multiparts. Then you can convert that to wkt with ogr2ogr.


Hopefully this makes sense.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...