Skip to content

New Globe Minimap is instead of updating the existing one in Shiny app #98

@ar-puuk

Description

@ar-puuk

As discussed in #97.

Hi, posting this here because I am not sure if this is a bug or (my) skill issue.

I am trying to create a shiny app using mapgl, and I have this issue where a new globe minimap is added when the geographic location on the map changes. This results in the following: (I changed the states from Colorado, California, Arizona, and Arkansas)

image

I was wondering if there is a way for the globe minimap to update rather than it being added every time a different state is selected?

# Minimal reprex for mapgl add_globe_minimap bug(?)

library(shiny)
library(mapgl)
library(sf)
library(tigris)
library(dplyr)

# Cache option for tigris
options(tigris_use_cache = TRUE)

# Prepare simple state geometries
states_sf <- tigris::states() |>
  sf::st_transform(crs = 3857) |>
  sf::st_zm(drop = TRUE, what = "ZM")

ui <- shiny::fluidPage(
  mapgl::story_maplibre(
    map_id      = "map",
    sections    = list(
      "intro" = mapgl::story_section(
        title   = "US States Explorer",
        content = list(
          shiny::selectInput(
            inputId = "state",
            label   = "Select a state:",
            choices = state.name,
            selected = "Colorado"
          )
        )
      )
    )
  )
)

server <- function(input, output, session) {

  # Reactive: geometry for selected state
  sel_state <- reactive({
    states_sf |> dplyr::filter(NAME == input$state)
  })

  # Initial map render
  output$map <- mapgl::renderMaplibre({
    mapgl::maplibre(
      style      = mapgl::carto_style("voyager"),
      bounds     = sel_state(),
      scrollZoom = FALSE
    ) |>
      mapgl::set_projection("globe") |>
      mapgl::add_globe_minimap(position = "bottom-right") |>
      mapgl::add_layer(
        id      = "state_outline",
        type = "fill",
        source  = sel_state(),
        paint = list(
          "fill-color" = "rgba(0,0,0,0)",
          "fill-outline-color" = "red"
        )
      )
  })


  # On entering the intro section, zoom to the selected state via proxy
  mapgl::on_section("map", "intro", {
    req(input$state)
    mapgl::maplibre_proxy("map") |>
      mapgl:: set_filter(
        layer_id = "state_outline",
        filter   = list("==", "NAME", input$state)
      ) |>
      mapgl::fit_bounds(
        sel_state(),
        animate = TRUE
      )
  })
}

shinyApp(ui, server)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions