3

I am experimenting with the leaflet package for some maps in Shiny. I would like to be able to have a base map that data will change and subsequently be remapped. However, I am trying to use the leafletProxy function whereby there is a base map and I just change the data points that are added. All of this works however the map doesn't zoom to the datapoints location. It remains at the farthest zoom.

enter image description here

The code to reproduce the problem:

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)

I would like the map to automatically zoom in once new points have been added.

2 Answers 2

5

try to add argument "fitBounds" in leafletProxy()

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

I revised G. Cocca's answer (mostly by adding a dataframe of "points") to get this:

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)
2
  • You call leafletProxy twice in the observeEvent. You can delete the first code block.
    – SeGa
    Commented Oct 1, 2018 at 14:21
  • Excellent catch, @SeGa. I revised.
    – dca
    Commented Oct 1, 2018 at 16:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.