更改 Shiny 应用传单地图中缩放控件的默认位置

Change the default position of zoom control in leaflet map of Shiny app

我正在使用 Shiny 应用程序创建传单地图,但想将缩放控件的默认位置从 topleft 更改为 topright

R leaflet 包在源代码中将默认位置设置为 topleft

根据这个问题:Customize Zoom in/out button in leaflet.js,我们可以使用map.zoomControl.setPosition('topright');来改变缩放控件的位置。

var map = L.map('map', {
  zoomControl: true
});
map.zoomControl.setPosition('topright');

我可以创建一个 R 函数来设置 zoomControl 的新位置吗?例如,

zoomControlPosition <- function(map, position = 'topleft') {
    # New codes add here
}

估计涉及到一些js,但我没有js的经验。感谢您的任何建议。

我想出了如何改变 zoomControl 的位置。您可以从我的传单包分支中找到此功能:https://github.com/byzheng/leaflet/commit/fdf9fb159adbc0e36cc2bd7d7b33c72c17c468f6

这是使用它的最小示例:

library(shiny)
library(leaflet)


ui <- fluidPage(
  leafletOutput("mymap")
)

server <- function(input, output, session) {
  output$mymap <- renderLeaflet({
    leaflet() %>%
      addTiles() %>%

      zoomControlPosition('topright')
  })
}

shinyApp(ui, server)

虽然我没有尝试过,但我认为邦优给了你一个完全回答你问题的答案。

出于两个原因,我仍然想分享我对这个问题的处理方法:

  • 它可以轻松灵活地以多种方式修改您的 zoomControl(仅适用于 R)
  • 它不修改传单包,因此您可能对所有即将发布的传单版本都满意。

方法是使用 actionButtons 自定义缩放控件。

在服务器中

  • 以反应值跟踪当前地图视图。 (我不仅将其用于缩放控制)
  • 在按下相应的操作按钮时向上或向下设置视图 (setView)。

添加到 server.R

# Zoom control - zoom out
observeEvent(input$map_zoom_out ,{
  leafletProxy("map") %>% 
    setView(lat  = (input$map_bounds$north + input$map_bounds$south) / 2,
            lng  = (input$map_bounds$east + input$map_bounds$west) / 2,
            zoom = input$map_zoom - 1)
})
# Zoom control - zoom in
observeEvent(input$map_zoom_in ,{
  leafletProxy("map") %>% 
    setView(lat  = (input$map_bounds$north + input$map_bounds$south) / 2,
            lng  = (input$map_bounds$east + input$map_bounds$west) / 2,
            zoom = input$map_zoom + 1)
})

我喜欢在 UI 中添加带动作按钮的绝对面板,但将按钮放在您喜欢的位置。

在ui.R中添加:

absolutePanel(
  top = "auto", left = "auto", right = 20, bottom = 20,
  width = "auto", height = "auto",
  actionButton("map_zoom_in", "+"),
  actionButton("map_zoom_out", "-")
)

这允许您更改默认位置并选择任何位置。不要忘记使用

禁用服务器中的标准缩放控件
leaflet(options = leafletOptions(zoomControl = FALSE))

希望有价值。

最好的, 吉都亚历山大

试试这个:

leaflet(options = leafletOptions(zoomControl = FALSE)) %>%
    htmlwidgets::onRender("function(el, x) {
        L.control.zoom({ position: 'topright' }).addTo(this)
    }") %>%