I have a PostGIS layer with linestring and I am trying to write the layer to shapefile using fiona and shapely.
Here is what I have so far:
from shapely.geometry import mapping,LineString
from shapely.wkt import loads,load
import fiona
from fiona.crs import from_epsg
import psycopg2
conn = psycopg2.connect("dbname='postgres',etc..) #connecting to DB
cur = conn.cursor() #setting up connection cursor
crs = from_epsg(4269)
schema = {'geometry': 'LineString', 'properties': {'State': 'str', 'Date': 'str'}}
with fiona.open(r"routes.shp", "w", "ESRI Shapefile", schema, crs) as output:
cur.execute("""select state,date,ST_AsText(geom) from trips;""")
rows = cur.fetchall()
conn.commit()
for row in rows:
print row
g = loads(row[2])
output.write({'properties':{'State': row[0], 'Date': row[1]},
'geometry': mapping(g)})
It throws an error when it gets to:
('South Dakota', '2016-06-19', 'LINESTRING(-103.8036896 44.4258771)')
Traceback (most recent call last):
File "C:\Users\Ralph\Documents\PythonScripts\LocationHistory.py", line 57, in <module>
g = loads(row[2])
File "C:\Python27\ArcGIS10.1\lib\site-packages\shapely\wkt.py", line 10, in loads
return geom_from_wkt(data) #factory(geom)
File "C:\Python27\ArcGIS10.1\lib\site-packages\shapely\geometry\base.py", line 55, in geom_from_wkt
"Could not create geometry because of errors while reading input."
ReadingError: Could not create geometry because of errors while reading input.
I used the same select query in postgres on the routes table and
('South Dakota', '2016-06-19', 'LINESTRING(-103.8036896 44.4258771)')
seems to be the error.
It writes the shapefile up to this record. what is strange is if I export the table to a shapefile using the PostGIS shapefile and dbf loader it exports the entire layer to a shapefile correctly.
My question is twofold:
How did postgis make a linestring from only one coordinate? How would I go about circumventing this problem?
shapefile from PostGIS - this record ('South Dakota', '2016-06-19', 'LINESTRING(-103.8036896 44.4258771)')
which throws the error in shapely when trying to create a linestring (because it is only 1 coordinate) shows up in the PostGIS shapefile as a record with no geometric attribute