Friday, 7 July 2017

postgresql - SQL query to have a complete geojson feature from PostGIS?


I would like to get a geojson feature with properties from PostGIS. I have found an example to have a feature collection but I can't make it works for just a feature.


SELECT row_to_json(fc)
FROM ( SELECT 'FeatureCollection' As type, array_to_json(array_agg(f)) As features
FROM (SELECT 'Feature' As type
, ST_AsGeoJSON(lg.geog)::json As geometry

, row_to_json(lp) As properties
FROM locations As lg
INNER JOIN (SELECT loc_id, loc_name FROM locations) As lp
ON lg.loc_id = lp.loc_id ) As f ) As fc;

so far I tryed to modify the feature collection query of the example. but the output is not valid.



Answer



This answer could be used with PostgreSQL version anterior to 9.4. Use dbaston's answer for PostgreSQL 9.4+


The query is the following: (where 'GEOM' is the geometry field, id the field to include in json properties, shapefile_feature the table name, and 489445 is the id of the feature wanted)


SELECT row_to_json(f) As feature \

FROM (SELECT 'Feature' As type \
, ST_AsGeoJSON('GEOM')::json As geometry \
, row_to_json((SELECT l FROM (SELECT id AS feat_id) As l)) As properties \
FROM shapefile_feature As l WHERE l.id = 489445) As f;

output:


{
"geometry":{
"type":"MultiPolygon",
"coordinates":[

[
[
[
-309443.24253826,
388111.579584133
],
[
-134666.391073443,
239616.414560895
],

[
-308616.222736376,
238788.813082666
],
[
-309443.24253826,
388111.579584133
]
]
]

]
},
"type":"Feature",
"properties":{
"feat_id":489445
}
}

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...