Search code examples
rshinyr-leaflet

Shiny Leaflet Map with Multiple Observers


I have two datasets which are subset using a sliderInput that selects for a range of dates. The filtered data then shows the latitude and longitude (based ont the zipcode) of certain events (weed and shops) within the range of dates selected. When I render the leaflet map however, only one set of datapoints ever shows up. If I comment out the first set observe function I can see the second set of datapoints and visa versa but I can never get both observers to show both sts of datapoints at the same time.

Dataset 1 (Weed)

                Date   Zip      MainSource
 2014-01-03 17:35:00 98103 Marijuana Plant
 2014-01-04 22:53:00 98112      Other Food
 2014-01-13 22:50:00 98272 Marijuana Plant
 2014-01-14 17:50:00 99210 Marijuana Plant
 2014-01-29 19:27:00 99302             thc
 2014-02-03 11:55:00 99336            Misc
                 ...   ...             ...

Dataset 2 (Shops)

                       name   zip    opening
             The Stash Box 98002 2014-11-21
                 Greenside 98198 2015-01-01
                Bud Nation 98106 2015-06-29
 West Seattle Cannabis Co. 98168 2015-02-28
               Nimbin Farm 98168 2015-04-25
              Have a Heart 98178 2015-04-24
                       ...   ...        ...

Leaflet Map Code

Here is the code for the leaflet map.

library(htmltools)
library(dplyr)
library(zipcode)
library(leaflet)
data(zipcode)

ui <- bootstrapPage(
    tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
    leafletOutput("map", width = "100%", height = "100%"),

    # Get user input for selected date range
    absolutePanel(top = 10, right = 12,
                  sliderInput("range", 
                      "Choose your dates:", 
                      min(weed$Date),
                      max(weed$Date), 
                      value = range(weed$Date), 
                      step = 0.1,       
                      timeFormat = "%b-%d-%Y"
                  )
    )
)

server <- function(input, output, session) {
    
    # Reactive expression for the data subsetted to what the user selected

    filteredData <- reactive({ 
            df <- weed[weed$Date >= input$range[1] & weed$Date <= input$range[2],] %>% 
                    group_by(Zip) %>% 
                    summarize(count = n())
                    names(df) <- c("zip", "count") 
                    df <- join(df, zipcode[,c(1,4,5)], by = "zip")
            return(df)
            })
    
    filteredShopData <- reactive({ 
            df <- shops[shops$opening >= input$range[1] & shops$opening <= input$range[2],] %>% 
                    group_by(zip) %>% 
                    summarize(count = n())
                    names(df) <- c("zip", "count") 
                    df <- join(df, zipcode[,c(1,4,5)], by = "zip")
            return(df)
    })

# Plot static map
    output$map <- renderLeaflet({
            leaflet() %>% addProviderTiles("CartoDB.Positron") %>% 
                    setView(lng = -122.213380, lat = 47.595225, zoom = 10)
    })
    
    # Plot pot shops
    observe({
          if (nrow(filteredShopData()) == 0) {leafletProxy("map") %>% clearShapes()} 
          else {
          leafletProxy("map", data = filteredShopData()) %>%
                    clearShapes() %>%
                    addCircles(~longitude, 
                               ~latitude, 
                               radius = ~500*sqrt(count), 
                               color = "black")
          }
     })
    
    # Plot cases in WA state
       observe({
            if (nrow(filteredData()) == 0) {leafletProxy("map") %>% clearShapes()} 
            else {
            leafletProxy("map", data = filteredData()) %>%
                    clearShapes() %>%
                             addCircles(~longitude, 
                                        ~latitude, 
                                        weight = 1, 
                                        radius = ~700*sqrt(count), 
                                        color = "red") }
    })
 
}

shinyApp(ui, server)

Solution

  • I think this has to do with the fact that you are passing two data arguments.

    instead I would directly call your data

    observe({
          if (nrow(filteredShopData()) == 0) {leafletProxy("map") %>% clearShapes()} 
          else {
          leafletProxy("map") %>%
                    clearShapes() %>%
                    addCircles(filteredShopData()$longitude, 
                               filteredShopData()$latitude, 
                               radius = ~500*sqrt(count), 
                               color = "black")
          }
     })
    
    # Plot cases in WA state
       observe({
            if (nrow(filteredData()) == 0) {leafletProxy("map") %>% clearShapes()} 
            else {
            leafletProxy("map") %>%
                    clearShapes() %>%
                             addCircles( filteredData()$longitude, 
                                         filteredData()$latitude, 
                                        weight = 1, 
                                        radius = ~700*sqrt(count), 
                                        color = "red") }
    })