OGR Cookbook

The OGR Simple Features Library contains three command-line tools for performing common operations on vector-based spatial data. Although the recipes shown here use shapefiles from the Global Administrative Areas database, OGR reads from and writes to many other formats.

If you’re an Ubuntu user it’s easy to download and install OGR, which is part of GDAL, the Geospatial Data Abstraction Library:

sudo apt-get install gdal-bin

If you’re a Mac user, visit the KyngChaos Wiki and download and install GDAL. If you’re a Windows user, download and install FWTools.


How do I find a shapefile’s coordinate system?

The following command returns each layer’s name, geometry, feature count, extent, coordinate system, and attributes:

ogrinfo -al -so HTI_adm3.shp

How do I transform a shapefile from one coordinate system to another?

Here, we transform from EPSG:4326 (WGS 84) to EPSG:32718 (UTM 18S). For convenience, source files are in src and destination files are in dst. Notice that the parameters are ordered destination—source, rather than the more common source—destination:

ogr2ogr -t_srs EPSG:32718 dst/HTI_adm3.shp src/HTI_adm3.shp

How do I read a shapefile but write a GeoJSON file?

There are many other formats, besides GeoJSON, to read from and write to. However, GeoJSON is especially useful for displaying spatial data on the Web.

ogr2ogr -f "GeoJSON" dst/CZE_adm2.json src/CZE_adm2.shp

How do I transform latitudes and longitudes in a CSV file from one coordinate system to another?

Create an XML control file to describe the structure of the CSV file. This file should have the extension .vrt but should not have an XML declaration. It helps to create this file incrementally, checking each increment with ogrinfo. The -skipfailures parameter can be useful when the transformation process fails unexpectedly, as it reports a useful error message to the screen. The -lco parameter allows you to control how the transformed latitudes and longitudes appear. Refer to the Creation Issues section of the Comma Separated Values page for more information. Notice that the source is the XML control file, not the CSV file.

ogr2ogr -skipfailures -t_srs EPSG:32718 -f "CSV"
dst/hcm_cleaned.csv src/hcm_cleaned.vrt

Note that if you use -lco SEPARATOR=TAB to write a tab-separated values file, the destination file should still have the extension .csv.

What does “FAILURE: Unable to open datasource…” mean?

It might mean that your source and destination parameters are in the wrong order: they should be given as destination—source, rather than the more common source—destination.