Search code examples
rrasterhttrrgdalgeotiff

R: reading geotiff data straight from web url (httr::GET raw content)


I would like to create a RasterLayer from GeoTIFF data provided by a server. I'll query the server for this data using a httr::GET call (the data is provided on-demand, so in the application there won't be a url ending in .tif but a query url).

After writing the result of this call to disk as a GeoTIFF file it's easy enough to create the RasterLayer from the resulting GeoTIFF file on disk:

library(httr)
library(raster)

url <- 'http://download.osgeo.org/geotiff/samples/gdal_eg/cea.tif'

geotiff_file <- tempfile(fileext='.tif')
httr::GET(url,httr::write_disk(path=geotiff_file))
my_raster <- raster(geotiff_file)
my_raster

However, I would like to skip the write to disk part and create the raster straight from the in-memory server response.

response <- httr::GET(url,httr::write_memory())
response

The content of the response is a raw string which I would need to interpret as geoTIFF data.

str(httr::content(response))

However, I can only find raster or rgdal functions to read from a file. Any suggestions on translating this raw string to a raster?

Thanks!


Solution

  • GDAL has some cool virtual file system driver, one of which is /vsicurl that

    allows on-the-fly random reading of files available through HTTP/FTP web protocols, without prior download of the entire file. It requires GDAL to be built against libcurl.

    Since the raster package builds on rgdal you can simply do this:

    library(raster)
    
    r <- raster('/vsicurl/http://download.osgeo.org/geotiff/samples/gdal_eg/cea.tif')
    
    plot(r)
    

    enter image description here