Change the default position of zoom control in leaflet map of Shiny app
Try this:
leaflet(options = leafletOptions(zoomControl = FALSE)) %>% htmlwidgets::onRender("function(el, x) { L.control.zoom({ position: 'topright' }).addTo(this) }") %>%
I figure out how to change the position of zoomControl
. You can find this feature from my fork of leaflet package: https://github.com/byzheng/leaflet/commit/fdf9fb159adbc0e36cc2bd7d7b33c72c17c468f6
This is an minimum example to use it:
library(shiny)library(leaflet)ui <- fluidPage( leafletOutput("mymap"))server <- function(input, output, session) { output$mymap <- renderLeaflet({ leaflet() %>% addTiles() %>% zoomControlPosition('topright') })}shinyApp(ui, server)
Even though I haven't tried it I think Bangyou gave you an answer that exactly answers your question.
I'd still like to share my approach to this issue for two reasons:
- It gives easy flexibility to modify your zoomControl in many ways (working only in R)
- It doesn't modify the leaflet package, so your probably good with all upcoming leaflet releases.
The approach is to customise the zoomcontrol with actionButtons.
In the server
- Keep track of current map view in reactive values. (I use this for more than just zoom control)
- Set the view (setView) up or down when the respective action button is pressed.
Add to server.R
# Zoom control - zoom outobserveEvent(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 inobserveEvent(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)})
I like to add absolutepanels in the UI with actionButtons, but place the buttons where you like.
In ui.R add:
absolutePanel( top = "auto", left = "auto", right = 20, bottom = 20, width = "auto", height = "auto", actionButton("map_zoom_in", "+"), actionButton("map_zoom_out", "-"))
This allows you to change the default position and choose any position. Don't forget to disable the standard zoom control in the server with
leaflet(options = leafletOptions(zoomControl = FALSE))
Hope it's valuable.
Best,Jiddu Alexander