It's strange to get such self intersecting polygons because it violates the polygon definition in OGC Simple feature access specification and may not be viewed as legal polygons.
I don't use GDAL that often, but am quite familiar with GEOS and if I remember clearly GDAL union/polygonize are built based on GEOS library. In GEOS, if you union two polygons that share one vertex coordinates, like the case in your given picture, it will return you a multipolygon. In case you might want to look into the code, here is how GEOS do it:
http://svn.osgeo.org/geos/branches/3.3/src/geom/
The relevant functions may be the Geometry::Union
in file Geometry.cpp
And also the GeometryFactory::buildGeometry
in file GeometryFactory.cpp
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)),...
Best Answer
If you have a simple Multipolygon such as the one below,
then using Javascript/Nodejs you can access each constituent Polygon using forEach, and write out a new Polygon using JSON.stringify
You could also access them directly in a loop, if you prefer a less functional way, indexed on mp.coordinates.length eg,
If you are dealing with a FeatureCollection, where you might have an array of feature, each containing a MultiPolygon, eg,
Then, you can use forEach to get to each feature, and then access each Polygon within each Multipolygon simply by looping through the array, as the first dimension of the coordinates array, is the index into each Polygon. Note, you can also save the properties, and assign them to each new Polygon feature.
If you want something more sophisticated, you could look into modifying the OpenLayers.Format.GeoJSON class.