[GIS] Clip specific layer by bounding box with ogr2ogr

ogrogr2ogrr

I am looking to use ogr2ogr to clip a specific layer (Towns) from an sqlite/gpkg data source to a bounding box. R is not necessary for running the code below it just makes it reproducible by providing an example dataset. Here is what I've tried:

library(sf)
input_gpkg <- system.file("sqlite/test3.sqlite", package = "sf")
st_layers(input_gpkg)

Driver: SQLite

Available layers:

layer_name geometry_type features fields

1 Towns Point 8101 5

2 HighWays Line String 10 2

3 Regions Multi Polygon 10 2

system(paste("ogr2ogr -f 'GPKG' -clipsrc 1077228.72991008 4218298.82092178 1211486.08907174 4469736.19302021 output.gpkg", input_gpkg))
st_layers("output.gpkg")

Driver: GPKG

Available layers:

layer_name geometry_type features fields

1 Towns Point 433 5

2 Regions Multi Polygon 1 2

3 HighWays Line String 0 2

I tried setting the clipsrclayer flag but I get the same result.

system(paste("ogr2ogr -f 'GPKG' -clipsrc 1077228.72991008 4218298.82092178 1211486.08907174 4469736.19302021 -clipsrclayer 'Towns' output.gpkg", input_gpkg))
st_layers("output.gpkg")

Driver: GPKG

Available layers:

layer_name geometry_type features fields

1 Towns Point 433 5

2 Regions Multi Polygon 1 2

3 HighWays Line String 0 2

How can I have the output contain only the Towns layer? I do not want a solution that involves loading the entire Towns layer into memory because of the possibility that it will involve a huge number of points and kill performance.

See also:

Best Answer

How to select a specific layer with ogr2ogr is documented in http://www.gdal.org/ogr2ogr.html but not in an ultimately clear way.

src_datasource_name
               [-lco NAME=VALUE] [-nln name]
               [-nlt type|PROMOTE_TO_MULTI|CONVERT_TO_LINEAR|CONVERT_TO_CURVE]
               [-dim XY|XYZ|XYM|XYZM|2|3|layer_dim] [layer [layer ...]]

The layer name(s) are given after the name of the datasource by using space as a separator.

This should work for you:

ogr2ogr -f 'GPKG' -clipsrc 1077228.72991008 4218298.82092178 1211486.08907174 4469736.19302021 output.gpkg input_gpkg Towns

Alternatively you can select whatever you want with SQL:

ogr2ogr -f 'GPKG' -clipsrc 1077228.72991008 4218298.82092178 1211486.08907174 4469736.19302021 -sql "select * from Towns" output.gpkg input_gpkg
Related Question