R interactive maps with multiple layers

1.2k Views Asked by At

I'm trying to create a map of US states comparing two variables, over time. I'd like to make this web based, and interactive. I've successfully done this combining R, leaflet, and Shiny. However, it is really really slow:

datadrivers.shinyapps.io/opioid_map/

I've followed the R leaflet instructions to use leafletProxy to update the layers I'm interested in, rather than redraw the entire map. I've also tried restricting the map bounds with the hopes that it wouldn't have to render as much data. It still takes 4-5 seconds to update when the slider moves. That's too slow.

I've looked at some of the other nice web maps through rMaps and googleVis, but as far as I can tell they only allow one map layer at a time - I need to present two variables. For example, with googleVis I can use gvisGeoChart to place either the markers or the polygons, but not both on the same map.

My last alternative is to simply create a static map in something like maptools, which I suppose will be faster, but they are not interactive so I'd prefer to avoid that route if possible.

I'd appreciate any guidance on optimizing further leaflet, or take advantage of another package that allows me to overlay multiple variables (I may not fully understand how to take advantage of rMaps or googleVis in this way).

FYI, here's my server code from the Shiny app. Unfortunately I can't give you the data for this one:

server <- function(input, output, session) {
  output$mymap<-renderLeaflet({
    pal <- colorNumeric(
      palette = "Blues",
      domain = us_state@data$death_rate_2014
    )
    leaflet(us_state) %>% addTiles() %>%
      setView(lng = -96, lat = 38, zoom = 3) %>%
      addLegend(position = "topright",
                pal = pal, values = ~death_rate_2014,
                title = "Deaths by Drug Poisoning, per 100,000",
                opacity = 1) %>%
      setMaxBounds(-72, 40, -70, 43)

  })
  observe({
    pal <- colorNumeric(
      palette = "Blues",
      domain = get(paste0("death_rate_",input$timeSlider),us_state@data)
    )
      leafletProxy("mymap",data=us_state) %>%
      #clearShapes %>% #Commented this step out-clearing the map each time adds a step and confuses the user
      addPolygons(stroke=FALSE,smoothFactor=.2,fillOpacity=.5,
                  color=~pal(get(paste0("death_rate_",input$timeSlider),us_state@data)),
                  popup=~get(paste0("death_rate_",input$timeSlider),us_state@data)) %>%
      addCircles(data=state.centroids2,lat=~Y,lng=~X,
                 radius=~get(paste0("kids_rate_",input$timeSlider),state.centroids2)*250,
                 weight=1,color="red",popup=
                   paste("Foster Care Caseload:",
                         as.character(round(get(paste0("kids_rate_",input$timeSlider),state.centroids2))),
                         "per 100,000"))
  })
}
0

There are 0 best solutions below