Name

ST_AsGeoJSON — Return the geometry as a GeoJSON element.

Synopsis

text ST_AsGeoJSON(geometry geom, integer maxdecimaldigits=15, integer options=0);

text ST_AsGeoJSON(geography geog, integer maxdecimaldigits=15, integer options=0);

text ST_AsGeoJSON(integer gj_version, geometry geom, integer maxdecimaldigits=15, integer options=0);

text ST_AsGeoJSON(integer gj_version, geography geog, integer maxdecimaldigits=15, integer options=0);

Description

Return the geometry as a Geometry Javascript Object Notation (GeoJSON) element. (Cf GeoJSON specifications 1.0). 2D and 3D Geometries are both supported. GeoJSON only support SFS 1.1 geometry type (no curve support for example).

The gj_version parameter is the major version of the GeoJSON spec. If specified, must be 1. This represents the spec version of GeoJSON.

The third argument may be used to reduce the maximum number of decimal places used in output (defaults to 15).

The last 'options' argument could be used to add Bbox or Crs in GeoJSON output:

  • 0: means no option (default value)

  • 1: GeoJSON Bbox

  • 2: GeoJSON Short CRS (e.g EPSG:4326)

  • 4: GeoJSON Long CRS (e.g urn:ogc:def:crs:EPSG::4326)

Version 1: ST_AsGeoJSON(geom) / maxdecimaldigits=15 version=1 options=0

Version 2: ST_AsGeoJSON(geom, maxdecimaldigits) / version=1 options=0

Version 3: ST_AsGeoJSON(geom, maxdecimaldigits, options) / version=1

Version 4: ST_AsGeoJSON(gj_version, geom) / maxdecimaldigits=15 options=0

Version 5: ST_AsGeoJSON(gj_version, geom, maxdecimaldigits) / options=0

Version 6: ST_AsGeoJSON(gj_version, geom, maxdecimaldigits, options)

Availability: 1.3.4

Availability: 1.5.0 geography support was introduced.

Changed: 2.0.0 support default args and named args.

This function supports 3d and will not drop the z-index.

Examples

GeoJSON format is generally more efficient than other formats for use in ajax mapping. One popular javascript client that supports this is Open Layers. Example of its use is OpenLayers GeoJSON Example

SELECT ST_AsGeoJSON(the_geom) from fe_edges limit 1;
					   st_asgeojson
-----------------------------------------------------------------------------------------------------------

{"type":"MultiLineString","coordinates":[[[-89.734634999999997,31.492072000000000],
[-89.734955999999997,31.492237999999997]]]}
(1 row)
--3d point
SELECT ST_AsGeoJSON('LINESTRING(1 2 3, 4 5 6)');

st_asgeojson
-----------------------------------------------------------------------------------------
 {"type":"LineString","coordinates":[[1,2,3],[4,5,6]]}