mapboxer icon indicating copy to clipboard operation
mapboxer copied to clipboard

How I can fly to bounds?

Open therotten24 opened this issue 3 years ago • 1 comments

Hi and thanks for reading me. I'm making a map with your awesome package and I want to update the coordinates of the map with a proxy function, but instead of going from one place to another it generates the map again. The code is as follows:

I don't know how I can do this correctly Do you have an idea of how I can fix it?

Thanks for the help

library(shiny)
library(mapboxer)
library(COVID19)
library(countrycode)

paises <- countrycode::codelist$country.name.en

shinyApp(
  ui = fluidPage(
    column(
      width = 12, align = "center",
      selectInput("var", "variable", 
                  choices = paises)
    ),
    mapboxerOutput("mapa")
  ),
  server = function(input, output, session){
    
    map_rendered <- reactiveVal(FALSE)
    output$mapa <- renderMapboxer({
      map_rendered(FALSE)
      casos <- COVID19::covid19(country = input$var  ) 
      mapboxer(
        style = basemaps$Carto$positron,
        center = c( head(casos$longitude,1),head(casos$latitude,1)),
        zoom = 4,
        maxZoom = 3,
        #minZoom = 6,
        pitch = 30,
        bearing = 0
      ) |> 
        fit_bounds(
          bounds = c(head(casos$longitude,1),head(casos$latitude,1),
                     head(casos$longitude,1),head(casos$latitude,1))
        ) 
      
    })
    
    
    observeEvent(input$var, {
      req(map_rendered())
      mapboxer_proxy("mapa") |> 
        #set_data(data = sf_shape, source_id = "mb") |> 
        #fit_bounds(sf::st_bbox(sf_shape)) |> 
        fit_bounds(
          bounds = c(head(casos$longitude,1),head(casos$latitude,1),
                     head(casos$longitude,1),head(casos$latitude,1))
        ) |> 
        update_mapboxer()
    }) 
    
  }
)


therotten24 avatar Nov 03 '21 05:11 therotten24

Hi @therotten24, the problem in your code is that you use a reactive variable when initializing the map:

# ...
casos <- COVID19::covid19(country = input$var  ) 
# ...

Therefore, every time input$var changes, the map is rendered again. You need to update casos in observeEvent and render the map with an initial value for casos.

See also this example on how to do it.

crazycapivara avatar Nov 04 '21 11:11 crazycapivara