Extracting Features from a Vector Layer

Suppose you want to extract features from a vector layer to create a smaller subset. This can be very handy if you have a large dataset and need just a portion of it for your current project. If your data happens to be in one of the formats supported by OGR, you can use ogr2ogr to create a new layer.

First let’s look at extracting by a simple bounding box. Say we want to pull Canada, United States, and Mexico from the world_borders shapefile. This can easily be done with a small bounding box that crosses each of the countries:

ogr2ogr -spat -111 20 -108 56 northamerica.shp world_borders.shp

The result is shown below, with the new shapefile (northamerica.shp) shown in green. For reference, the bounding box used to extract the features is shown in red/orange.




All features that intersect the bounding box are included in the new layer. We could tweak the box a bit to pick up more of Canada to the north and Alaska to the west, however you can easily see that it would be difficult to specify a bounding box to get all of Canada down to Mexico without snagging Greenland as well as Cuba, Haiti, and so forth.

The second way to extract features is by attribute. In this case, we use a simple where clause with ogr2ogr to specify which countries we want in the new layer:

ogr2ogr -where "CNTRY_NAME='Canada' or CNTRY_NAME='Mexico' or CNTRY_NAME='United States' northamerica2.shp world_borders.shp
This creates a new layer with all the polygons for the three countries:




To determine which field name to use in the where clause, load the layer in to QGIS, uDig, OpenJUMP, etc and use the identify tool to examine a few features before using ogr2ogr. You can also get a list of the fields in a layer using ogrinfo.

As you can see, ogr2ogr provides two quick ways to subset your data and create new layers for any OGR supported format. See the documentation for ogr2ogr for information on specifying different output formats and options.

March 28, 2008 · admin · No Comments
Tags: ,  · Posted in: OGR