terrainr v0.3.1


Monthly downloads



Landscape Visualizations in R and 'Unity'

Functions for the retrieval, manipulation, and visualization of 'geospatial' data, with an aim towards producing '3D' landscape visualizations in the 'Unity' '3D' rendering engine. Functions are also provided for retrieving elevation data and base map tiles from the 'USGS' National Map ('<https://apps.nationalmap.gov/services/>').


terrainr: Landscape Visualization in R and Unity

MIT CRAN status Lifecycle:
maturing codecov Project Status: Active – The project has reached a stable, usable
state and is being actively
developed. R build
status rOpenSci Review


terrainr makes it easy to retrieve elevation and base map image tiles for areas of interest within the United States from the National Map family of APIs, and then process that data into larger, joined images or crop it into tiles that can be imported into the Unity 3D rendering engine.

There are three main utilities provided by terrainr. First, users are able to download data from the National Map via the get_tiles function, downloading data tiles for the area represented by an sf or Raster object:


# Optional way to display a progress bar while your tiles download:

simulated_data <- data.frame(id = seq(1, 100, 1),
                             lat = runif(100, 44.04905, 44.17609), 
                             lng = runif(100, -74.01188, -73.83493))

simulated_data <- st_as_sf(simulated_data, coords = c("lng", "lat"))
simulated_data <- st_set_crs(simulated_data, 4326)

with_progress( # Only needed if you're using progressr
  output_tiles <- get_tiles(simulated_data,
                            services = c("elevation", "ortho"),
                            resolution = 90 # pixel side length in meters

Once downloaded, these images are in standard GeoTIFF or PNG formats and can be used as expected with other utilities:


raster::plotRGB(raster::brick(output_tiles[["ortho"]][[1]]), scale = 1)

Secondly, terrainr provides functions for manipulating these files, editing downloaded images to create new base map tiles:

vector_overlay <- vector_to_overlay(

vector_overlay <- combine_overlays(


Finally, terrainr helps you visualize this data, both natively in R via the new geom_spatial_rgb geom:

ggplot() + 
  geom_spatial_rgb(data = output_tiles[["ortho"]],
                   aes(x = x, y = y, r = red, g = green, b = blue)) + 
  geom_sf(data = simulated_data)

As well as with the Unity 3D rendering engine, allowing you to fly or walk through your downloaded data sets in 3D and VR:

with_progress( # When not specifying resolution, default is 1m pixels
  output_tiles <- get_tiles(simulated_data,
                            services = c("elevation", "ortho"))

merged_dem <- merge_rasters(output_tiles[["elevation"]], 
                            tempfile(fileext = ".tif"))
merged_ortho <- merge_rasters(output_tiles[["ortho"]], 
                              tempfile(fileext = ".tif"))

mapply(function(x, y) raster_to_raw_tiles(input_file = x, 
                                          output_prefix = tempfile(), 
                                          side_length = 4097, 
                                          raw = y),
       c(merged_dem, merged_ortho),
       c(TRUE, FALSE))

# We can then import these tiles to Unity to create:

The more time intensive processing steps can all be monitored via the progressr package, so you’ll be more confident that your computer is still churning along and not just stalled out. For more information, check out the introductory vignette and the guide to importing your data into Unity!

Available Datasets

The following datasets can currently be downloaded using get_tiles or hit_national_map_api:

  • 3DEPElevation: The USGS 3D Elevation Program (3DEP) Bare Earth DEM.
  • USGSNAIPPlus: National Agriculture Imagery Program (NAIP) and high resolution orthoimagery (HRO).
  • nhd: A comprehensive set of digital spatial data that encodes information about naturally occurring and constructed bodies of surface water (lakes, ponds, and reservoirs), paths through which water flows (canals, ditches, streams, and rivers), and related entities such as point features (springs, wells, stream gauges, and dams).
  • govunits: Major civil areas for the Nation, including States or Territories, counties (or equivalents), Federal and Native American areas, congressional districts, minor civil divisions, incorporated places (such as cities and towns), and unincorporated places.
  • contours: The USGS Elevation Contours service.
  • geonames: Information about physical and cultural geographic features, geographic areas, and locational entities that are generally recognizable and locatable by name.
  • NHDPlus_HR: A comprehensive set of digital spatial data comprising a nationally seamless network of stream reaches, elevation-based catchment areas, flow surfaces, and value-added attributes.
  • structures: The name, function, location, and other core information and characteristics of selected manmade facilities.
  • transportation: Roads, railroads, trails, airports, and other features associated with the transport of people or commerce.
  • wbd: Hydrologic Unit (HU) polygon boundaries for the United States, Puerto Rico, and the U.S. Virgin Islands.

(All descriptions above taken from the National Map API descriptions.)


You can install the development version of terrainr from GitHub with:

# install.packages("devtools")

Code of Conduct

Please note that this package is released with a Contributor Code of Conduct. By contributing to this project, you agree to abide by its terms.


Functions in terrainr

Name Description
combine_overlays Combine multiple image overlays into a single file
geom_spatial_rgb Plot RGB rasters in ggplot2
addbuff Add a uniform buffer around a bounding box
get_tiles A user-friendly way to get USGS National Map data tiles for an area
georeference_overlay Georeference image overlays based on a reference raster
get_centroid Get the great-circle centroid for latitude/longitude data
calc_haversine_distance Extract latitude and longitude from a provided object
deg_to_rad Convert decimal degrees to radians
hit_national_map_api Hit the USGS 3DEP API and retrieve an elevation heightmap
raster_to_raw_tiles Crop a raster and convert the output tiles into new formats.
terrainr_coordinate_pair-class S4 class for coordinate points in the format expected by terrainr functions.
vector_to_overlay Turn spatial vector data into an image overlay
terrainr-package terrainr: Landscape Visualizations in R and 'Unity'
point_from_distance Find latitude and longitude for a certain distance and azimuth from a point.
terrainr_coordinate_pair Construct a terrainr_coordinate_pair object.
rad_to_deg Convert radians to degrees
merge_rasters Merge multiple raster files into a single raster
terrainr_bounding_box-class S4 class for bounding boxes in the format expected by terrainr functions.
terrainr_bounding_box Construct a terrainr_bounding_box object
No Results!

Vignettes of terrainr

No Results!

Last month downloads


Type Package
URL https://docs.ropensci.org/terrainr/, https://github.com/ropensci/terrainr
BugReports https://github.com/ropensci/terrainr/issues
License MIT + file LICENSE
Encoding UTF-8
LazyData true
RoxygenNote 7.1.1
Config/testthat/parallel true
Config/testthat/edition 3
VignetteBuilder knitr
NeedsCompilation no
Packaged 2021-02-22 16:46:14 UTC; mikemahoney218
Repository CRAN
Date/Publication 2021-02-23 08:30:02 UTC

Include our badge in your README