Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Render a shapefile to a png and display it in your terminal, in one command
# make a temporary directory and push it on to the stack
tmp=$(mktemp -d); pushd $tmp && \
# get a US map at 20m resolution and unzip it
curl -s https://www2.census.gov/geo/tiger/GENZ2018/shp/cb_2018_us_region_20m.zip -o us.zip && \
unzip -q us.zip && \
# rasterize the map's only layer, using the `ALAND` feature. Restrict the
# bounding box (-te) to the continental US, because the map includes Alaska
# and Hawaii and Guam, and we're not going to bother with those here
# (sorry!). -ts sets the output size to 1200x800, then we give the input and
# output files.
gdal_rasterize -l cb_2018_us_region_20m -a ALAND \
-te -124.848974, 24.396308, -66.885444, 49.384358 \
-ts 1200 800 \
cb_2018_us_region_20m.shp us.tiff && \
# now convert the geotiff we just generated to a png
gdal_translate us.tiff us.png && \
# display it, and return to the initial directory
imgcat us.png && popd

To figure out what layer and field you want to render, use ogrinfo:

$ ogrinfo -al -so cb_2018_us_region_20m.shp
INFO: Open of `cb_2018_us_region_20m.shp'
      using driver `ESRI Shapefile' successful.

Layer name: cb_2018_us_region_20m
Metadata:
  DBF_DATE_LAST_UPDATE=2019-04-15
Geometry: Polygon
Feature Count: 4
Extent: (-179.174265, 18.917466) - (179.773922, 71.352561)
Layer SRS WKT:
GEOGCS["NAD83",
    DATUM["North_American_Datum_1983",
        SPHEROID["GRS 1980",6378137,298.257222101,
            AUTHORITY["EPSG","7019"]],
        TOWGS84[0,0,0,0,0,0,0],
        AUTHORITY["EPSG","6269"]],
    PRIMEM["Greenwich",0,
        AUTHORITY["EPSG","8901"]],
    UNIT["degree",0.0174532925199433,
        AUTHORITY["EPSG","9122"]],
    AUTHORITY["EPSG","4269"]]
REGIONCE: String (1.0)
AFFGEOID: String (10.0)
GEOID: String (1.0)
NAME: String (100.0)
LSAD: String (2.0)
ALAND: Integer64 (14.0)
AWATER: Integer64 (14.0)

The above tells us that there's one layer, cb_2018_us_region_20m with is specified in (I think) the EPSG:4269 coordinate system

That layer has 7 features (again, I think): REGIONCE, AFFGEOID, GEOID, NAME, LSAD, ALAND, AWATER which you can give as arguments to -a in the gdal_rasterize command

I could not figure out how to just render the continental US, so I just clipped the render to the continental US' bounding box using -te and some coordinates I looked up on the web

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment