Tomaž Bratanič
Tomaž Bratanič

Reputation: 6534

Shapefile to csv with a WKT multipolygon column

My data is from census maps. I am not familiar with shapefiles or WKT file, but I managed to find this solution, on by which I tried to create my own code.

import ogr
import csv

#Open files
csvfile=open("states_wkt.csv",'wb')
ds=ogr.Open("cb_2015_us_state_20m.shp")
lyr=ds.GetLayer()

#Get field names
dfn=lyr.GetLayerDefn()
nfields=dfn.GetFieldCount()
fields=[]
for i in range(nfields):
    fields.append(dfn.GetFieldDefn(i).GetName())
fields.append('kmlgeometry')
csvwriter = csv.DictWriter(csvfile, fields)

While this works, i get geometry results looking like:

""kmlgeometry"":""<MultiGeometry>
<Polygon><outerBoundaryIs><LinearRing><coordinates>-118.593969,33.467198
-118.484785,33.487483 -118.370323,33.409285 -118.286261
</coordinates></LinearRing></outerBoundaryIs></Polygon>
 <Polygon><outerBoundaryIs><LinearRing><coordinates>-118.594033,33.035951
-118.540069,32.980933 -118.446771,32.895424 -118.353504,32.821962 -118.425634
</coordinates></LinearRing></outerBoundaryIs></Polygon>
</MultiGeometry>

In my specific case I would like to return geometry data in a form of multipolygon like this:

MULTIPOLYGON (((-71.6062550000000044 42.0133709999999994, 
-71.5276060000000058 42.0149979999999985, -71.5169060000000059 
42.0155979999999971, -71.4999080000000049 42.0171989999999980, 
-71.3814009999999968 42.0187979999999968, -71.3815050000000042 
42.0000110000000006, -71.3812010000000043 41.9811979999999991)))

How can I achieve that ?

Upvotes: 1

Views: 1911

Answers (1)

Tomaž Bratanič
Tomaž Bratanič

Reputation: 6534

I managed to find a simple script that is easy to use using GDAL:

ogr2ogr -f CSV multipolygon_states.csv cb_2015_us_state_20m.shp -nlt MULTIPOLYGON -lco GEOMETRY=AS_WKT

Upvotes: 1

Related Questions