PostGIS  2.1.10dev-r@@SVN_REVISION@@
Datum LWGEOM_asGeoJson ( PG_FUNCTION_ARGS  )

Definition at line 367 of file lwgeom_export.c.

References dumpnode::geom, getSRSbySRID(), gserialized_get_srid(), lwfree(), lwgeom_free(), lwgeom_from_gserialized(), lwgeom_to_geojson(), result, and SRID_UNKNOWN.

368 {
369  GSERIALIZED *geom;
370  LWGEOM *lwgeom;
371  char *geojson;
372  text *result;
373  int srid;
374  int version;
375  int option = 0;
376  int has_bbox = 0;
377  int precision = DBL_DIG;
378  char * srs = NULL;
379 
380  /* Get the version */
381  version = PG_GETARG_INT32(0);
382  if ( version != 1)
383  {
384  elog(ERROR, "Only GeoJSON 1 is supported");
385  PG_RETURN_NULL();
386  }
387 
388  /* Get the geometry */
389  if (PG_ARGISNULL(1) ) PG_RETURN_NULL();
390  geom = (GSERIALIZED *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
391 
392  /* Retrieve precision if any (default is max) */
393  if (PG_NARGS() >2 && !PG_ARGISNULL(2))
394  {
395  precision = PG_GETARG_INT32(2);
396  if ( precision > DBL_DIG )
397  precision = DBL_DIG;
398  else if ( precision < 0 ) precision = 0;
399  }
400 
401  /* Retrieve output option
402  * 0 = without option (default)
403  * 1 = bbox
404  * 2 = short crs
405  * 4 = long crs
406  */
407  if (PG_NARGS() >3 && !PG_ARGISNULL(3))
408  option = PG_GETARG_INT32(3);
409 
410  if (option & 2 || option & 4)
411  {
412  srid = gserialized_get_srid(geom);
413  if ( srid != SRID_UNKNOWN )
414  {
415  if (option & 2) srs = getSRSbySRID(srid, true);
416  if (option & 4) srs = getSRSbySRID(srid, false);
417  if (!srs)
418  {
419  elog( ERROR,
420  "SRID %i unknown in spatial_ref_sys table",
421  srid);
422  PG_RETURN_NULL();
423  }
424  }
425  }
426 
427  if (option & 1) has_bbox = 1;
428 
429  lwgeom = lwgeom_from_gserialized(geom);
430  geojson = lwgeom_to_geojson(lwgeom, srs, precision, has_bbox);
431  lwgeom_free(lwgeom);
432 
433  PG_FREE_IF_COPY(geom, 1);
434  if (srs) pfree(srs);
435 
436  result = cstring2text(geojson);
437 
438  lwfree(geojson);
439 
440  PG_RETURN_TEXT_P(result);
441 }
void lwfree(void *mem)
Definition: lwutil.c:190
LWGEOM * lwgeom_from_gserialized(const GSERIALIZED *g)
Allocate a new LWGEOM from a GSERIALIZED.
void lwgeom_free(LWGEOM *geom)
Definition: lwgeom.c:1006
char ** result
Definition: liblwgeom.h:218
LWGEOM * geom
#define SRID_UNKNOWN
Unknown SRID value.
Definition: liblwgeom.h:154
char * lwgeom_to_geojson(const LWGEOM *geo, char *srs, int precision, int has_bbox)
Takes a GEOMETRY and returns a GeoJson representation.
Definition: lwout_geojson.c:35
char * getSRSbySRID(int srid, bool short_crs)
Definition: lwgeom_export.c:39
int32_t gserialized_get_srid(const GSERIALIZED *s)
Extract the SRID from the serialized form (it is packed into three bytes so this is a handy function)...
Definition: g_serialized.c:70

Here is the call graph for this function: