[GIS] dissolve polygons of GeoJSON with gdal/ogr

dissolvegdalgeojsonogrpolygon

I have a GeoJSON with only polygons in it. I have to dissolve (merge) the polygons with the same "DN"-value. I found out that you can do it with shapefiles like this:

ogr2ogr outputfile.shp inputfile.shp -dialect sqlite -sql “SELECT dissolvefield,ST_Union(geometry) as geometry FROM inputfile GROUP BY dissolvefield”

but since I dont know shp nor SQL I don't know how to apply that to GeoJSON and "DN"-value. I hope someone can help me out here.

{
    "type": "FeatureCollection",

    "features": [
    { "type": "Feature", "properties": { "DN": "0" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 1425, 0 ], [ 1425, 1 ], [ 1592, 0 ], [ 1425, 0 ] ] ] } },
    { "type": "Feature", "properties": { "DN": "1" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 4397, 88 ], [ 4397, 89 ], [ 4398, 88 ], [ 4397, 88 ] ] ] } },
    { "type": "Feature", "properties": { "DN": "2" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 369, 93 ], [ 369, 101 ], [ 371, 93 ], [ 369, 93 ] ] ] } },
    { "type": "Feature", "properties": { "DN": "2" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 368, 106 ], [ 368, 107 ], [ 369, 106 ], [ 368, 106 ] ] ] } }
    ]
}

EDIT:
I think I had a wrong Idea what "dissolve" is. So I want to explain what I want more detailed: I only want to MERGE two or more polygons with the SAME DN-Value AND which are neighbours. So that Polygons which were splitted due to tiles are unified again.

Best Answer

Since OGR version 1.10.0 the sqlite SQL dialect has been able to be applied to any spatial datset. Which is great, as it means that you can apply it to your GeoJSON files.

Looking at the OGR GeoJSON documentation you can see that the layer name for a GeoJSON file is OGRGeoJSON which means that the SQL that selects from the GeoJSON file will translate from the sample above to:

SELECT DN, ST_Union(geometry) as geometry FROM OGRGeoJSON GROUP BY DN

Note the union will merge all polygons within regardless of whether or not they touch, so pass in the -explodecollections parameter to ogr2ogr.

So assuming your input file is input.geojson and you want to create output.geojson the full command is:

ogr2ogr -f GeoJSON -explodecollections output.geojson input.geojson -dialect sqlite -sql "SELECT DN as DN, ST_Union(geometry) as geometry FROM OGRGeoJSON GROUP BY DN"