Search code examples
rshinyr-leaflet

addPolygons in leaflet in R shiny destroys reactivity


I am trying to overlay a heatmap of polygons on my map and then be able to zoom into different parts of it depending on user input.

The code works fine when I remove the heatmap. The user is able to jump around from place to place (based on a dropdown list).

With the polygons it works the first time fully,

the second dropdown choice causes just a map to show with no polygons and the location does not shift,

and the third dropdown choice nothing shows.

output$HMmapstation <- renderLeaflet({ 
 x <- NA
 x <- input$HMstation #picking the place to view
 x <- leaflet_map %>% setView(preloaded_stations[which(preloaded_stations$name == x),]$longitude,
                         preloaded_stations[which(preloaded_stations$name == x),]$latitude,
                         zoom = 14) %>% clearShapes()
 x <- x %>% addPolygons(data=polys_dat, color = ~pal(polys_dat@plotOrder),
                                smoothFactor=.1, stroke = FALSE, fillOpacity = 0.1)
 x 

})

The leaflet map is created globally above the server and is as follows:

leaflet_map <- (leaflet() %>%
              addProviderTiles("OpenStreetMap.BlackAndWhite",
                               options = providerTileOptions(noWrap = TRUE,minZoom=9)) %>%#~pal(seq(1,537,1))~rainbow(50, start=0,end=.3, alpha = NULL)
              setMaxBounds(-0.715485, 51.252031, 0.514984, 51.745313))

I just cant seem to figure out why it would work once and then stop. Especially since without the polygon it works as expected.


Solution

  • Leaflet is an amazing addition to R's quiver, I am starting to use it quite a bit at work and at times I also struggle with lost functionality as layers build. I do not have an answer for you working directly in R, but I have a suggestion.

    One of the things that I am discovering as I become a Javascript D3 developer is that the last object into a JS visualization is on top.

    So this means as you stack polygons, lines, and other objects and data onto a map, it is possible to BLOCK the visibility/functionality of objects below it.

    If you are familiar with Javascript, you could open the devtools in chrome and look to see how the layers are being applied to the map.

    As you do this, try to think about how R will call out to JS to compile the web graphic it makes and then see if you can re-order something in your R stack, or turn a shape into an outline so that the shape below retains function.

    And it is possible after the graphic is "extruded' from R to go in and manually tweak the javascript controlling the features you are using with a lot more control than you have in R itself. I have done some editing on the resulting file set successfully.

    There is a LOT more help in working on leaflet in JS directly here and around the web. You may be able to find a quicker answer that way.