2

I'm trying to create a geofence/circle from a lat/long set and I'm close except that the GeoJSON that PostGIS creates differs in structure from the client library that our front-end uses. Here is my python to create the geofence:

session = DatabaseSessionService().create_session()
METERS_IN_HALF_MILE = 805
longitude = 21.304116745663165
latitude = 38.68607570952619
geom = func.ST_Buffer(func.ST_MakePoint(longitude, latitude), METERS_IN_HALF_MILE)
geofence = Geofence(
 geom=geom,
 geojson=cast(func.ST_AsGeoJSON(geom), JSON),
 company_id=188,
 name='Test Fence 1'
)
session.add(geofence)
session.commit()

This will create a record with geojson set to:

{
 "type":"Polygon",
 "coordinates":[
 [
 [
 826.304116745663,
 38.6860757095262
 ],
 ...
 ]
 ]
}

However I'd like to maintain the convention set previously and have the GeoJSON written as a Feature Object like this:

{
 "type":"Feature",
 "properties":{
 },
 "geometry":{
 "type":"Polygon",
 "coordinates":[
 [
 [
 -92.29188859462738,
 38.913722221672636
 ],
 ...
 ]
 ]
 }
}

I've looked into using ogr2ogr but I'd prefer that this be an automated process that happens on creation as opposed to being a post-creation task.

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Jun 28, 2016 at 20:20
2

1 Answer 1

2

I ended up doing an INSERT and then UPDATE to use the python libs geojson and shapely to generate the geoJSON. So my code now looks like this.

import geojson
from models import Geofence
from geoalchemy2.shape import to_shape
from sqlalchemy import func
from services.DatabaseSessionService import DatabaseSessionService
session = DatabaseSessionService().create_session()
longitude = -92.339292
latitude = 39.005994
geom = func.ST_Buffer(func.ST_MakePoint(longitude, latitude), 0.5)
geofence = Geofence(
 geom=geom,
 company_id=188,
 name='Test Fence 1',
 alert_enter=False,
 alert_exit=False
)
session.add(geofence)
session.commit()
geometry = to_shape(geofence.geom)
geofence.geojson = geojson.Feature(geometry=geometry, properties={})
session.add(geofence)
session.commit()
answered Jun 28, 2016 at 22:45
1
  • Could this be of any help? It describes the way to create valid GeoJSON within the PostGIS database. Commented Sep 8, 2017 at 6:38

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.