Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to connect leaflet map clicks (events) with plot creation in a shiny app #74

Open
makis23 opened this issue Feb 26, 2018 · 0 comments

Comments

@makis23
Copy link

makis23 commented Feb 26, 2018

Hello I am creating an environmental shiny app in which I want to use a leaflet map to create some simple plots. Below I create a sample of my initial data frame:

location = c("100 ail","16th and Whitmore","40AB01 - ANTWERPEN") 
lastUpdated = c("2018-02-01 09:30:00", "2018-02-01 03:00:00", "2017-03-07 10:00:00") 
firstUpdated = c("2015-09-01 00:00:00","2016-03-06 19:00:00","2016-11-22 15:00:00")
pm25=c("FALSE","FALSE","FALSE")
pm10=c("TRUE","FALSE","FALSE")
no2=c("TRUE","FALSE","FALSE")
latitude=c(47.932907,41.322470,36.809700)
longitude=c(106.92139000,-95.93799000
,-107.65170000)

df = data.frame(location, lastUpdated, firstUpdated,latitude,longitude,pm25,pm10,no2)

As a general idea I want to be able to click on a certain location in the map based on this dataframe. Then I have one selectInput() and 2 dateInput(). The 2 dateInput() should take as inputs the df$firstUpdated and df$lastUpdated respectively. Then the selectInput() should take as inputs the pollutants that exist in the df based on "TRUE"/"FALSE" value. And then the plots should be created. All of these should be triggered by clicking on the map.

Up to now I was not able to achieve this so in order to help you understand I connected the selectInput() and the dateInput() with input$loc which is a selectIpnut() with locations in the first tab as I will not need this when I find the solution.

#ui.r
library(shiny)
library(leaflet)
library(plotly)
library(shinythemes)
library(htmltools)
library(DT)

# Define UI for application that draws a histogram
navbarPage("ROPENAQ",
           tabPanel("CREATE DATAFRAME",
                    sidebarLayout(

                      # Sidebar panel for inputs ----
                      sidebarPanel(
                        wellPanel(
                          uiOutput("loc"),
                          helpText("Choose a Location to create the dataframe.")
                        )
                        ),
                      mainPanel(

                      )
                    )
           ),
           tabPanel("LEAFLET MAP",
                    leafletOutput("map"),
                    wellPanel(
                      uiOutput("dt"),
                      uiOutput("dt2"),
                      helpText("Choose a start and end date for the dataframe creation. Select up to 2 dates")
                    ),
                    "Select your Pollutant",
                    uiOutput("pollutant"),





                    helpText("While all pollutants are listed here, not all pollutants are measured at all locations and all times.  
                             Results may not be available; this will be corrected in further revisions of the app.  Please refer to the measurement availability 
                             in the 'popup' on the map."),

                    hr(),
                    fluidRow(column(8, plotOutput("tim")),
                             column(4,plotOutput("polv"))),
                    hr(),

                    fluidRow(column(4, plotOutput("win")),
                             column(8,plotOutput("cal"))),
                    hr(),
                    fluidRow(column(12, plotOutput("ser"))
                             )
           )


)



#server.r
# server.R for emission dashboard
# load packages
library(utilr)
library(openair)
library(plotly)
library(dplyr)
library(ggplot2)
library(shiny)
library(gissr)
library(ropenaq)
library(worldmet)

# load data
# veh_data_full <- readRDS("veh_data_full.RDS")
# veh_data_time_var_type <- readRDS("veh_data_time_var_type.RDS")
df$location <- gsub( " " , "+" , df$location)
shinyServer(function(input, output, session) {




    output$pollutant<-renderUI({
      selectInput("pollutant", label = h4("Choose Pollutant"), 
                  choices = colnames(df[,6:8]), 
                  selected = 1)
    })


    #Stores the value of the pollutant selection to pass to openAQ request



    ###################################
   #output$OALpollutant <- renderUI({OALpollutant})


    ##################################
    # create the map, using dataframe 'locations' which is polled daily (using ropenaq)
    #MOD TO CONSIDER: addd all available measurements to the popup - true/false for each pollutant, and dates of operation.



    output$map <- renderLeaflet({
      leaflet(subset(df,(df[,input$pollutant]=="TRUE")))%>% addTiles() %>%
        addMarkers(lng = subset(df,(df[,input$pollutant]=="TRUE"))$longitude, lat = subset(df,(df[,input$pollutant]=="TRUE"))$latitude,
                   popup = paste("Location:", subset(df,(df[,input$pollutant]=="TRUE"))$location, "<br>",
                                 "Pollutant:", input$pollutant, "<br>",
                                 "First Update:", subset(df,(df[,input$pollutant]=="TRUE"))$firstUpdated, "<br>",
                                 "Last Update:", subset(df,(df[,input$pollutant]=="TRUE"))$lastUpdated
                                 ))
    })
    #Process Tab
   OAL_site <- reactive({
        req(input$map_marker_click)
        location %>%
            filter(latitude == input$map_marker_click$lat,
                   longitude == input$map_marker_click$lng)

###########
        #call Functions for data retrieval and processing.  Might be best to put all data request
        #functions into a seperate single function.  Need to:
        # call importNOAA() to retrieve meteorology data into temporary data frame
        # call aq_measurements() to retrieve air quality into a temporary data frame
        # merge meteorology and air quality datasets into one working dataset for computations; temporary
        # meteorology and air quality datasets to be removed.
        # call openAir() functions to create plots from merged file.  Pass output to a dashboard to assemble 
        # into appealing output.
        # produce output, either as direct download, or as an emailable PDF.
        # delete all temporary files and reset for next run.
    })
   #fun 

   output$loc<-renderUI({
     selectInput("loc", label = h4("Choose location"),
                 choices = df$location ,selected = 1
     )
   })



   output$dt<-renderUI({

                 dateInput('date',
                           label = 'First Available Date',
                           value = subset(df$firstUpdated,(df[,1]==input$loc))
                 )           


   })
   output$dt2<-renderUI({

                 dateInput('date2',
                           label = 'Last available Date',
                           value = subset(df$lastUpdated,(df[,1]==input$loc))
                 )            


   })

   rt<-reactive({


     AQ<- aq_measurements(location = input$loc, date_from = input$dt,date_to = input$dt2,parameter = input$pollutant)
     met <- importNOAA(year = 2014:2018)
     colnames(AQ)[9] <- "date"
     merged<-merge(AQ, met, by="date")
     # date output -- reports user-selected state & stop dates in UI
     merged$location <- gsub( " " , "+" , merged$location)

     merged


   })
   #DT  



     output$tim = renderPlot({
       timeVariation(rt(), pollutant = "value")
     })
     output$polv = renderPlot({
       percentileRose(rt(), pollutant = "value", smooth  =TRUE)
     })
     output$win = renderPlot({
       windRose(rt(),key.footer = "knots")
     })
     output$cal = renderPlot({
       calendarPlot(rt(), pollutant = "value") 
     })
     output$ser = renderPlot({
       timePlot(rt(), pollutant = "value") 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant