score:0

While the drilldown feature of highcharter is useful, when you have data in every state, it would require loading the map for each underlying state at render. An approach I have taken is to essentially switch between plotting the state map and a county map as follows.

## Library
library(shiny)
library(shinyjs)
library(dplyr)
library(highcharter)
library(stringr)

## Load maps at start for speed
maps <- sapply(
  X = c("us-all", "us-tx-all"),
  simplify = FALSE,
  FUN = function(x) { highcharter::download_map_data(paste0("countries/us/", x)) }
)

ui <- shiny::fluidPage(
  shinyjs::useShinyjs(),
  highcharter::highchartOutput(outputId = "map"),
  shiny::uiOutput(outputId = "ui")
)

server <- function(input, output, session) {
  ## USA map with just TX as example
  state_map <- shiny::reactive({
    highcharter::highchart() %>%
      highcharter::hc_add_series_map(
        map = maps[["us-all"]],
        df = data.frame(state_abbr = c("TX"), y = c(10)),
        joinBy = c("postal-code", "state_abbr"),
        value = "y"
      ) %>%
      highcharter::hc_plotOptions(
        series = list(
          allowPointSelect = TRUE,
          events = list(
            click = htmlwidgets::JS(
              "function(event) {
                 Shiny.setInputValue(
                   'geo_click', 
                   event.point.state_abbr, 
                   {priority: 'event'}
                 );
              }"
            )
          )
        )
      )
  })

  ## County map
  county_map <- shiny::reactive({
    highcharter::highchart() %>%
      highcharter::hc_add_series_map(
        map = maps[[paste0("us-", stringr::str_to_lower(input$geo_click), "-all")]],
        df = data.frame(city = c("Gray", "Leon", "Lamb", "Duval"), y = c(1, 4, 2, 3)),
        joinBy = c("name", "city"),
        value = "y"
      )
  })

  ## Set to state map at outset
  output$map <- highcharter::renderHighchart({ state_map() })

  ## If state clicked, add button to go back to state map
  output$ui <- shiny::renderUI({
    if (!is.null(input$geo_click)) {
      shiny::actionButton(
        inputId = "geo_button",
        label = "Return to USA Map"
      )
    }
  })

  ## If button clicked, reset input, hide button, and go back to state map
  shiny::observeEvent(
    eventExpr = input$geo_button,
    handlerExpr = {
      output$map <- highcharter::renderHighchart({ state_map() })
      shinyjs::hide(id = "geo_button")
    }
  )

  ## If state clicked, go to county map and show button
  shiny::observeEvent(
    eventExpr = input$geo_click,
    handlerExpr = {
      output$map <- highcharter::renderHighchart({ county_map() })
      shinyjs::show(id = "geo_button")
    }
  )
}

shiny::shinyApp(ui = ui, server = server)

Related Query

More Query from same tag