benfasoli
1/25/2018 - 8:39 PM

Overlay partial transparency gridded raster to grayscale Google Map terrain layer

Overlay partial transparency gridded raster to grayscale Google Map terrain layer

library(ggmap)
library(tidyverse)

# Fetch SLC-centric grayscale Google Map terrain layer
basemap <- get_googlemap(center = c(lon = -112.0, lat = 40.6), zoom = 10,
                         scale = 2, maptype = 'terrain', color = 'bw')

# Display downloaded map
ggmap(basemap)

# Create gridded example data
xyz <- expand.grid(x = seq(-112.4, -111.6, length.out = 100),
                   y = seq(40.3, 40.9, length.out = 100))
xyz$z <- with(xyz, abs(x * y))

# Define color palette for raster plotting
cp <- c('blue','cyan','white','yellow','orange','red')

# Convert baselayer to cartesian coordinates (Google Maps uses Mercator) and
# overlay color filled raster with partial opacity
ggmap(basemap) +
  coord_cartesian() +
  geom_raster(data = xyz, aes(x = x, y = y, fill = z), alpha = 0.7) +
  scale_fill_gradientn(colors = cp) +
  labs(x = NULL, y = NULL, fill = NULL) +
  theme(plot.margin = margin(0, 0, 0, 0, 'cm'))
ggsave('output-map-example.png')