Skip to content

Instantly share code, notes, and snippets.

@mdsumner
Created November 22, 2021 04:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdsumner/56509cf7731fae90db645c7908fc20a4 to your computer and use it in GitHub Desktop.
Save mdsumner/56509cf7731fae90db645c7908fc20a4 to your computer and use it in GitHub Desktop.
  library(sf)
#> Linking to GEOS 3.9.2, GDAL 3.3.2, PROJ 8.2.0
library(ggplot2)
library(rnaturalearth)

world_g <- st_graticule(ndiscr = 10000,
                        margin = 0.00000000001) |> 
  st_transform("+proj=adams_ws2") |> 
  st_geometry()

countries <- ne_countries(returnclass = "sf") |> 
  st_transform("+proj=adams_ws2")


## remotes::install_github("hypertidy/gdalio")
library(gdalio)
ve_src <- '<GDAL_WMS>
  <Service name="VirtualEarth">
    <ServerUrl>http://a${server_num}.ortho.tiles.virtualearth.net/tiles/a${quadkey}.jpeg?g=90</ServerUrl>
  </Service>
  <MaxConnections>4</MaxConnections>
  <Cache/>
</GDAL_WMS>'
gdalio_set_default_grid(list(extent = sf::st_bbox(world_g)[c(1, 3, 2, 4)], 
                             dimension = c(1024, 1024), 
                             projection = sf::st_crs(world_g)$wkt))
## get xyz in a matrix
#ve <- tibble::as_tibble(gdalio_xyz(ve_src, bands = 1:3, resample = "bilinear"))
#ve$rgb <- rgb(ve$Band1, ve$Band2, ve$Band3, maxColorValue = 255)


source(system.file("raster_format/raster_format.codeR", package = "gdalio", mustWork = TRUE))
## or, get as a terra object
ve_raster <- gdalio_terra(ve_src, bands = 1:3, resample = "bilinear")
## and apply the mask by the hull of the graticule
ve <- as.data.frame(terra::mask(ve_raster, terra::vect(sf::st_convex_hull(world_g))), 
                    xy = TRUE)
ve$rgb <- rgb(ve[[3]], ve[[4]], ve[[5]], maxColorValue = 255)

ggplot() + geom_raster(data = ve, aes(x, y, fill = rgb)) + scale_fill_identity() 
ggplot() +
  geom_raster(data = ve, aes(x, y, fill = rgb)) + scale_fill_identity() + 
  geom_sf(data = world_g, color = "white") + 
  geom_sf(data = sf::st_cast(countries, "MULTILINESTRING")) + 
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())

image

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