Skip to main content

toGeoJSON

Converts a geometry object to a GeoJSON Feature object or a GeoJSON FeatureCollection object.

This function has 2 overloads, when called with:

  • a single geometry object it returns a GeoJSON Feature object,
  • an array of geometry objects it returns a GeoJSON FeatureCollection object.

Type Parameters​

  • P - The type of geometry/feature properties

Parameters​

NameTypeDefaultDescription
geometryiesGeometry<P> | Geometry<P>[]The geometry object or the array of geometry objects to be converted into a GeoJSON object
options?objectOptional GeoJSON output configuration
options.flavor?'strict' | 'extended''strict'Geometry types support mode.
  • strict mode: only allows the 7 standard GeoJSON geometry types: Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon, and GeometryCollection. When an input geometry is not one of these types, an error will be thrown.
  • extended mode: allows serialization of all geometry types that GEOS supports, including curved geometries like CircularString, CompoundCurve, CurvePolygon, etc. The JSON structure of these geometries is not standardized and may change in future versions.
options.layout?'XY' | 'XYZ' | 'XYZM' | 'XYM''XYZ'Coordinate layout for the output GeoJSON.
Defines the coordinate structure of the output geometries.
Use this to:
  • Force 2D output by specifying 'XY'
  • Drop M ordinates while keeping Z ordinates with 'XYZ'
  • Drop Z ordinates while keeping M ordinates with 'XYM'
  • Keep both Z and M ordinates with 'XYZM'
⚠️ Warning: M ordinates (measure values) are not part of the official GeoJSON specification and may not be interpreted correctly by other parsers. Use 'XY' or 'XYZ' layouts for maximum interoperability.

Returns​

GeoJSON_Feature<GeoJSON_Geometry, P> | GeoJSON_FeatureCollection<GeoJSON_Geometry, P> | JSON_Feature<JSON_Geometry, P> | JSON_FeatureCollection<JSON_Geometry, P>

GeoJSON Feature or GeoJSON FeatureCollection object

Throws​

  • GEOSError (strict mode only) when called with not standard GeoJSON geometry

See also​

Examples​

'flavor' option
'layout' option
toGeoJSON(fromWKT('POINT ZM (1 2 3 4)'), { layout: 'XYZM' }); // will extract [ 1, 2, 3, 4 ]
toGeoJSON(fromWKT('POINT ZM (1 2 3 4)'), { layout: 'XYZ' }); // [ 1, 2, 3 ]
toGeoJSON(fromWKT('POINT ZM (1 2 3 4)'), { layout: 'XYM' }); // [ 1, 2, 4 ]
toGeoJSON(fromWKT('POINT ZM (1 2 3 4)'), { layout: 'XY' }); // [ 1, 2 ]
toGeoJSON(fromWKT('POINT M (1 2 4)'), { layout: 'XYZM' }); // [ 1, 2, NaN, 4 ]
toGeoJSON(fromWKT('POINT M (1 2 4)'), { layout: 'XYZ' }); // [ 1, 2 ]
toGeoJSON(fromWKT('POINT (1 2)'), { layout: 'XYZM' }); // [ 1, 2 ]
toGeoJSON(fromWKT('POINT (1 2)'), { layout: 'XYZ' }); // [ 1, 2 ]