[英]Shiny leaflet easyButton only fires once
我想要一個 Shiny + Leaflet 應用程序在全球和國家范圍之間輕彈。 單擊國家符號可按預期深入到該比例。 為了從國家視圖返回到全局視圖,我添加了一個 easyButton。 它適用於第一次點擊,但是當用戶再次向下鑽取到任何國家並點擊再次返回到全局視圖時,什么也沒有發生。 可重現的腳本:
require(shiny)
require(dplyr)
require(leaflet)
d = tibble(country = c(rep('China', 3), rep('Brazil', 3), rep('Canada', 3)),
name = paste(country, rep(1:3,3)), count = sample(30:100,9),
lon = c(105, 112, 110, -52, -54, -51, -95, -100, -93),
lat = c(35, 33, 25, -10, -11, -12, 60, 63, 61))
dSum = d %>% group_by(country) %>% summarise(lon = mean(lon), lat = mean(lat), count = sum(count)) %>% rename(name = country)
renderMap = function(x){
renderLeaflet({
leaflet(x) %>%
addCircleMarkers(layerId = ~name, lng = ~lon, lat = ~lat, label = ~ name, radius = ~ pmax(3, 100 * sqrt(count/max(count)))) %>%
addProviderTiles(providers$Stamen.TonerLite, options = providerTileOptions(noWrap = TRUE, minZoom=2, maxZoom=18)
) %>%
addEasyButton(easyButton(
icon="fa-backward", title="Refresh map", id = "refresh-map",
onClick = JS(" function(btn, map) { Shiny.onInputChange('my_easy_button', 'refresh'); }")))
})
}
server <- function(input, output, session) {
output$mymap <- renderMap(dSum)
# click on country
observeEvent(input$mymap_marker_click, {
countryname = input$mymap_marker_click$id
message(countryname)
output$mymap = renderMap(filter(d, country == countryname))
})
# click on refresh button
observeEvent(input$my_easy_button, { output$mymap = renderMap(dSum) })
}
ui <- fluidPage(
tags$head( tags$style(HTML("#mymap { position: fixed; left: 0; top: 0; width: 100vw; height: 100vh !important; }
.container-fluid { margin:0; padding:0; } ")) ),
leafletOutput("mymap")
)
shinyApp(ui, server)
使用 jQuery 模擬點擊時也可以看到效果 - 例如$('.easy-button-button').click()
。
知道為什么會這樣嗎?
它比你建議的更容易。 Shiny 僅對更改做出反應,因此您需要在 JS 函數調用中包含更改。 使用Math.random()
可以解決問題。
onClick = JS("function(btn, map){Shiny.onInputChange('easyButtonIdentify', Math.random());}")
根據本的評論:
<leaflet_obj> %>%
addEasyButton(easyButton(states = list(
easyButtonState(stateName = 'onestate',
icon="fa-backward", title="Refresh map", #id = "refresh-map",
onClick = JS(" function(btn, map) { Shiny.onInputChange('my_easy_button', 'refresh'); Shiny.onInputChange('my_easy_button', 'free'); }"))
)
))
})
}
不知道為什么會這樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.