R自动缩放在Shiny中更新了leafletProxy Map对象

时间:2015-10-19 14:12:00

标签: r shiny leaflet

我正在试验Shiny中某些地图的leaflet包。我希望能够有一个基础地图,数据将更改,然后重新映射。但是,我正在尝试使用leafletProxy函数,其中有一个基本映射,我只是更改添加的数据点。所有这些都可行,但地图不会缩放到数据点位置。它仍处于最远的变焦范围。

enter image description here

重现问题的代码:

library(shiny)
library(leaflet)

r_colors <- rgb(t(col2rgb(colors()) / 255))
names(r_colors) <- colors()

ui <- fluidPage(
  leafletOutput("mymap"),
  p(),
  actionButton("goButton", "New Points")
)

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

  output$mymap <- renderLeaflet({
    leaflet() %>%
      addProviderTiles("Stamen.TonerLite",
                       options = providerTileOptions(noWrap = TRUE)
      )
  })

  observeEvent(input$goButton, {
    points <- cbind(rnorm(40) * 2 + 13, rnorm(40) + 48)

    leafletProxy('mymap', session) %>%
      clearMarkers() %>%
      addMarkers(data = points)
  })
}

shinyApp(ui, server)

我希望地图在添加新点后自动放大。

2 个答案:

答案 0 :(得分:3)

尝试在leafletProxy()

中添加参数“fitBounds”
leafletProxy('mymap', session) %>%
  clearMarkers() %>%
  addMarkers(data = points) %>%
  fitBounds(lng1 = max(points$long),lat1 = max(points$lat),
            lng2 = min(points$long),lat2 = min(points$lat))

答案 1 :(得分:1)

我修改了G. Cocca的答案(主要是通过添加“点”的数据框)来获得此信息:

library(shiny)
library(leaflet)

r_colors <- rgb(t(col2rgb(colors()) / 255))
names(r_colors) <- colors()

ui <- fluidPage(
  leafletOutput("mymap"),
  p(),
  actionButton("goButton", "New Points")
)

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

  output$mymap <- renderLeaflet({
    leaflet() %>%
      addProviderTiles("Stamen.TonerLite",
                       options = providerTileOptions(noWrap = TRUE)
      )
  })

  observeEvent(input$goButton, {
    points <- data.frame("long" = rnorm(40) * 2 + 13, 
                            "lat" = rnorm(40) + 48)


    leafletProxy('mymap', session) %>%
      clearMarkers() %>%
      addMarkers(data = points) %>%
      fitBounds(lng1 = max(points$long),lat1 = max(points$lat),
                lng2 = min(points$long),lat2 = min(points$lat))


  })
}

shinyApp(ui, server)