# This map compares two netcdf files on leaflet. The leaflet views are synced.
# Michael Tso # github = cmtso
packrat::on()
library(shiny)
library(ncdf4)
library(raster)
library(leaflet)
library(leaflet.minicharts)
library('manipulateWidget') # sync leaflet
# can comment out after the first time
#download.file('https://www.unidata.ucar.edu/software/netcdf/examples/tos_O1_2001-2002.nc', 'tos_O1_2001-2002.nc','wget')
#download.file('https://www.unidata.ucar.edu/software/netcdf/examples/sresa1b_ncar_ccsm3-example.nc', 'sresa1b.nc','wget')
file1 <- "tos_O1_2001-2002.nc"
file2 <- "sresa1b.nc" # has multiple layers
da_list = c("Sea surface temperature","CCSM output (eastward wind)")
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Map comparison tool (Minimal example)"),
# Controls
sidebarLayout(
sidebarPanel(
selectInput('dataset1', "Select dataset 1 to plot:", da_list, da_list[1], multiple = FALSE),
selectInput('dataset2', "Select dataset 2 to plot:", da_list, da_list[2], multiple = FALSE),
),
# Show a plot of the generated distribution
mainPanel(
combineWidgetsOutput('TwoMaps', width = "100%", height = "600px")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
dataset1 <- reactive({input$dataset1})
dataset2 <- reactive({input$dataset2})
r1 <- reactive({
req(dataset1())
x <- ifelse(dataset1() == da_list[1], file1,
ifelse(dataset1() == da_list[2], file2,
NA))
r1 = raster(x)
r1
})
r2 <- reactive({
req(dataset2())
x <- switch(dataset2(),
"CCSM output (eastward wind)" = file2,
"Sea surface temperature" = file1)
r2 = raster(x)
r2
})
color_pal1 <- reactive({
colorNumeric(c("#0C2C84", "#41B6C4", "#FFFFCC"), values(r1()),
na.color = "transparent")
})
color_pal2 <- reactive({
colorNumeric(c("#0C2C84", "#41B6C4", "#FFFFCC"), values(r2()),
na.color = "transparent")
})
#Initialize map
output$TwoMaps = renderCombineWidgets({
mymap1 <- leaflet() %>% addTiles() %>%
addRasterImage(r1(),
colors = color_pal1(),
opacity = .7) %>%
setView(133.77,-25.27, zoom = 3) %>%
addLegend(
pal = color_pal1(), values = values(r1()),
title = "Map 1") %>%
syncWith("basicmaps")
mymap2 <- leaflet() %>% addTiles() %>%
addRasterImage(r2(),
colors = color_pal2(),
opacity = .7) %>%
setView(133.77,-25.27, zoom = 3) %>%
addLegend(
pal = color_pal2(), values = values(r2()),
title = "Map 2") %>%
syncWith("basicmaps")
combineWidgets(mymap1, mymap2, ncol = 2)
})
}
# Run the application
shinyApp(ui = ui, server = server)