In the concluding Q&A session of the Shiny workshop, a participant asked if it was possible to build functionality into a Shiny app where a user could upload a CSV of addresses then view the geocoded addresses on a map. This question was too lengthy to answer in the live session, but is very well-suited to a follow-up blog post!
I’m using the bslib package to set up the UI, which has become my framework of choice for building Shiny apps. page_sidebar() gets you a collapsible sidebar by default, and putting an output inside card() with full_screen = TRUE allows you to pop out the map to full screen.
fileInput() handles the user’s file uploads. As you’ll see in the video, users can drag-and-drop a CSV file to upload it or click the input button to browse their filesystem.
The conditionalPanel() is set up to appear only once a file is uploaded. It reveals a number of dropdown menus that will be populated with the column names of the input file (handled in the server code), and an action button to geocode the addresses. You’ll want to customize this depending on the expected input format of your CSV file and potentially include some error handling.
The reactive object df_to_geocode() represents the uploaded file. Once the file is uploaded, the drop-down menus are populated (using updateSelectInput()) with the column names of the uploaded file.
This code is critical to get the app to work correctly:
The reactive fileUploaded output returns TRUE or FALSE depending on whether or not a file has been uploaded, and is used to trigger the conditional panel. Setting suspendWhenHidden = FALSE in outputOptions() ensures that fileUploaded will update even when the UI element is hidden.
The app then observes the input$geocode button click event and uses mb_batch_geocode() to geocode the input addresses in bulk based on the user’s column selections. Note the use of bindEvent() instead of observeEvent(); this syntax was new to me, but is now recommended by Shiny’s developers for event handling.
How to learn more
If you are interested in learning more, be sure to check out the Location Intelligence and Shiny Web Apps Workshop Bundle, where you’ll get 5 hours of step-by-step instruction from me along with two annotated tutorials to help you build skills in geospatial analytics and Shiny. As a bonus - readers of this blog post get 25% off the purchase price with the code GEOCODE!