Importing geojson using geoalchemy2

858 views
Skip to first unread message

GrammyPuter

unread,
Jul 2, 2017, 12:48:51 PM7/2/17
to GeoAlchemy
Patience with someone who is trying to teach herself Geoalchemy.

I am moving to QGIS with PostGIS, coming from an ArcGIS background (all the way back to when it ran on Primes).

I am getting geojson from a rest query, and I need to import the polygon into PostGIS using GeoAlchemy. I really like the ORM, and I am trying to do it that way.

This works, but I suspect is a kludge, and there is an elegant way.

qString = "ST_AsText(ST_GeomFromGeoJSON('{\"type\":\"Polygon\", \"coordinates\":[[[-122.7606046, 47.2759964], [-122.7610586, 47.2755668], [-122.7616634, 47.2758681], [-122.7612063, 47.2762963], [-122.7606046, 47.2759964]]]}, 4326')) As wkt;"
query = session.query(qString)
rp = session.execute(query)
myGeom = rp.scalar()

myGeom is the geojson geometry to add to the polygon (there are many attributes, some of which I am editing prior to adding to PostGIS. So I also do a session.add(record).

Since I am sure there is a better way, I am open to suggestions. I don't like the two-transaction model.

Celeste

Eric Lemoine

unread,
Jul 2, 2017, 3:06:03 PM7/2/17
to geoal...@googlegroups.com
Hi!

You can use the "geojson" [1] and "shapely" [2] packages. For example:

----------
import geojson
from shapely.geometry import asShape
from geoalchemy.shape import from_shape


geojson_geom = geojson.loads(geojson_str)
geom = from_shape(asShape(geojson_geom))

record = Record()
record.geom = geom
session.add(record)
----------


There are other ways, but this is one.

Cheers,

[1] <https://pypi.org/project/geojson/>
[2] <https://pypi.org/project/Shapely/>


--
Eric
Reply all
Reply to author
Forward
0 new messages