Skip to content

Instantly share code, notes, and snippets.

@walkerke
Created December 14, 2021 18:48
Show Gist options
  • Save walkerke/f6c38aa374b8acc3867baa46f1bcad6f to your computer and use it in GitHub Desktop.
Save walkerke/f6c38aa374b8acc3867baa46f1bcad6f to your computer and use it in GitHub Desktop.
library(shiny)
library(leaflet)
library(mapboxapi)
library(glue)
# If publishing to a Shiny server you'll need to be explicit about your token
# Swap in your token for your tileset
mapbox_token <- "pk.ey..."
# Define a simple UI; set the default cursor to pointer
# so that users know to click on the tiles
ui <- fluidPage(
tags$style( '#map { cursor: pointer; }'),
fluidRow(
leafletOutput("map", height = "650")
)
)
# Server
server <- function(input, output) {
# Point Leaflet to the rendered style ID; I'm using a smaller
# scaling factor to make the labels bigger
output$map <- renderLeaflet({
# Make a legend that corresponds to the colors in the Mapbox Studio map
legend_ramp <- colorRampPalette(colors = c("#fe1616", "#ffffff", "#4150f1"))
legend_pal <- colorNumeric(legend_ramp(100), domain = 0:98)
# Render your Mapbox Studio style with your style ID and username
leaflet() %>%
addMapboxTiles(style_id = "ckhfebmo504c419n99lr29qbe",
username = "kwalkertcu",
scaling_factor = "0.5",
access_token = mapbox_token) %>%
setView(-97.177, 32.7, 10) %>%
addLegend(
position = "bottomright",
pal = legend_pal,
values = 0:98,
title = "% voting for<br/>President Biden"
)
})
# Reactive object that gives the coordinates of a clicked location
coords_click <- eventReactive(input$map_click, {
X <- input$map_click$lng
Y <- input$map_click$lat
return(c(X, Y))
})
# When a location is clicked, use query_tiles() to query
# the underlying tileset and format a popup based on the returned information
observeEvent(coords_click(), {
# query_tiles() requires XY coordinates and a tileset ID, which you can
# determine from Mapbox Studio.
location_info <- query_tiles(
location = coords_click(),
tileset_id = "kwalkertcu.tarrant_president",
access_token = mapbox_token
)
# query_tiles() returns a nested list of info
# which will correspond to your tileset. I'd recommend querying your tiles
# first outside of Shiny to see how you'll need to format what is returned
# when you are creating your popup HTML.
my_popup <- glue(
"<b>% Biden:</b> {round(location_info$features$properties$pct_biden, 1)}<br/><b>% Trump:</b> {round(location_info$features$properties$pct_trump, 1)}"
)
# Clear any existing popups and add a new one
leafletProxy("map") %>%
clearPopups() %>%
addPopups(lng = coords_click()[1],
lat = coords_click()[2],
popup = my_popup)
})
}
# Run the application
shinyApp(ui = ui, server = server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment