在Rshiny中将小册子映射缩放为默认值

时间:2015-10-01 21:20:16

标签: r leaflet shiny

无论如何都要添加图层控件或按钮来重置地图并返回初始位置。例如,当您正在探索地图并放大时,然后您想缩小以回到初始阶段。

library(shiny)
library(leaflet)

ui <- fluidPage(
  leafletOutput("mymap")

)

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

outline <- quakes[chull(quakes$long, quakes$lat),]

output$mymap <- renderLeaflet({ leaflet(quakes) %>%
  # Base groups
  addTiles(group = "OSM (default)") %>%
  addProviderTiles("Stamen.Toner", group = "Toner") %>%
  addProviderTiles("Stamen.TonerLite", group = "Toner Lite") %>%
  # Overlay groups
  addCircles(~long, ~lat, ~10^mag/5, stroke = F, group = "Quakes") %>%
  addPolygons(data = outline, lng = ~long, lat = ~lat,
              fill = F, weight = 2, color = "#FFFFCC", group = "Outline") %>%
  # Layers control
  addLayersControl(
    baseGroups = c("OSM (default)", "Toner", "Toner Lite"),
    overlayGroups = c("Quakes", "Outline"),
    options = layersControlOptions(collapsed = FALSE)
    )

  })
}

shinyApp(ui, server)

2 个答案:

答案 0 :(得分:5)

您可以在没有任何javascript代码的情况下执行此操作,方法是使用leafletProxysetView函数在单击按钮时更改地图。

以下是一个例子:

library(shiny)
library(leaflet)

ui <- fluidPage(
  leafletOutput("mymap"),
  actionButton("reset_button", "Reset view")

)

server <- function(input, output, session) {
  initial_lat = -23.079
  initial_lng = 178.15
  initial_zoom = 4

  output$mymap <- renderLeaflet({ leaflet(quakes) %>% 
                                    setView(lat = initial_lat, lng = initial_lng, zoom = initial_zoom) %>%
                                    addTiles(group = "OSM (default)") %>%
                                    addProviderTiles("Stamen.Toner", group = "Toner") %>%
                                    addProviderTiles("Stamen.TonerLite", group = "Toner Lite")})                                 


  observe({
    input$reset_button
    leafletProxy("mymap") %>% setView(lat = initial_lat, lng = initial_lng, zoom = initial_zoom)
  })
}

shinyApp(ui, server)

答案 1 :(得分:1)

是的,你可以。看一下传单的documentation

修改地图状态的方法 setView()

  

使用给定的&gt;设置地图的视图(地理中心和缩放)动画选项。

所以我要做的是在ui.R中加actionButtonobserveEvent()激活.js功能。闪亮可以与您可以阅读here.js个文件进行通信。

您必须适应代码的示例:

ui.R
actionButton("goButton", "Go!"),
p("Click the button to update the view.")

server.R
    observeEvent(input$goButton, {
    session$sendCustomMessage(type = "myCallbackHandler", Yourlatlng) //send to .js code snippet
})


//I would create a www file in the folder where server.R and ui.R is. By default shiny looks into this folder
 .js file
Shiny.addCustomMessageHandler("myCallbackHandler",function(Yourlatlng) {
var latlng = Yourlatlng;
setView(latlng, center,...) //check documentation for your specifcations
});