[GIS] Export polygon in geojson as multipolygon

geojsongeometrypostgisqgis

Anyone knows if is there any way to export a polygon layer in geojson, as multipolygon?

I have a multipolygon shapefile. But there are single and multi polygons.

When I export it to geojson, I got both structures:
Polygons with single feature, are exported as polygons (with 3 arrays)

 "type": "Polygon",
   "coordinates": [
       [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ],
       [ [100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2] ]
   ]

And some polygons formed by several features, are exported as multipolygon, with four arrays:

 "type": "MultiPolygon",
   "coordinates": [
       [
           [ [102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0] ]
       ],
       [
           [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ],
           [ [100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2] ]
       ]
   ]

What I need is to get a geojson that shows polygons and multipolygons with the second structure (four arrays)

Anyone could tell me if it is possible, or any clue on how to do it?

Best Answer

You can convert all your data into multipolygons with ogr2ogr by defining "new layer type" with -nlt MULTIPOLYGON. However, I am not sure if the result is exactly what you believe when multipolygon has only one part.

This is a triangle as polygon

{
"type": "FeatureCollection",

"features": [
{ "type": "Feature", "properties": { }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 95.0, 216.0 ], [ 241.0, 253.0 ], [ 175.0, 138.0 ], [ 95.0, 216.0 ] ] ] } }
]
}

This is the same triangle as multipolygon

{
"type": "FeatureCollection",

"features": [
{ "type": "Feature", "properties": { }, "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ 95.0, 216.0 ], [ 241.0, 253.0 ], [ 175.0, 138.0 ], [ 95.0, 216.0 ] ] ] ] } }
]
}

EDIT

However, if the aim is to combine all the separate features, both polygons and multipolygons into one feature which is of type multipolygon, you must build an union. If your mixture of polygons and multipolygons is in file "mix.shp" the command to use is:

ogr2ogr -f geojson union.json mix.shp -dialect sqlite -sql "select st_union(geometry) from mix"

The result "union.json " contains one multipolygon as can be seen from the ogr2ogr report:

Layer name: OGRGeoJSON
Geometry: Multi Polygon
Feature Count: 1
...
OGRFeature(OGRGeoJSON):0
  MULTIPOLYGON (((125 229,185 289,252 234,208 169,125 229)),...