0

I've got the coastline of Canada from OSM. For my work I only need the main landmass without any islands. Despite I was able to manually delete all the islands in JOSM / QGIS I need an automatic solution.

How to remove all polygons except the main one from a GeoJSON (or Shapefile) in commandline?


Even this simply doesn't work

ogr2ogr -f GeoJSON -dialect SQLITE -sql "SELECT * FROM Canada_1428125_AL2 order by ST_AREA(geometry) desc limit 1" out.geojson Canada_1428125_AL2.shp

because the multipolygon contains all islands. Is there any splitter function?

1

Based on this answer to Selecting features by attributes using ogr2ogr?, you could order by by perimeter or surface enclosed by the line and take only the first row with Limit 1

example:

ogr2ogr -sql "SELECT * FROM infile order by ST_AREA(ST_MakePolygon(geom)) desc limit 1" outfile.shp infile.shp

ST_MakePolygon creates a polygon from your lines. If you have polygons do not use the ST_MakePolygon statement. I understood the coastline as lines, that's why I used the ST_MakePolygon function.

  • You can sort on-the-fly by using GDAL SQLite dialect and function ST_Area. Could you try to edit your answer and give a complete usage example? – user30184 Jul 22 '18 at 7:47
  • Even this simply doesn't work ogr2ogr -f GeoJSON -dialect SQLITE -sql "SELECT * FROM Canada_1428125_AL2 order by ST_AREA(geometry) desc limit 1" out.geojson Canada_1428125_AL2.shp because the multipolygon contains all islands. Is there any splitter function? – Luis Paganini Jul 23 '18 at 10:24
1

You must do it in two steps:

Explode the multipolygon Use ogr2ogr with -explodecollections as documented in https://www.gdal.org/ogr2ogr.html

ogr2ogr -f "ESRI Shapefile" -explodecollections exploded_polygons.shp Canada_1428125_AL2.shp

Select the biggest of the exploded polygons like you have tried

ogr2ogr -f GeoJSON -dialect SQLITE -sql "SELECT * FROM exploded_polygons order by ST_AREA(geometry) desc limit 1" out.geojson exploded_polygons.shp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.