Skip to content

Instantly share code, notes, and snippets.

@kent37
Created March 22, 2018 19:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kent37/63c55c0bbdb0640d8c43369cdeeebdd2 to your computer and use it in GitHub Desktop.
Save kent37/63c55c0bbdb0640d8c43369cdeeebdd2 to your computer and use it in GitHub Desktop.
Leaflet map that toggles selection on click
# Draw a map which responds to clicks by toggling the selection state
# of the clicked polygon.
library(shiny)
library(leaflet)
library(sf)
library(tidyverse)
nc = read_sf(system.file("gpkg/nc.gpkg", package="sf")) %>%
st_transform(4326)
# Initial selection
nc$selected = sample(c(0, 1), nrow(nc), replace=TRUE)
ui <- fluidPage(
titlePanel("Leaflet selection demo"),
leafletOutput('map')
)
server <- function(input, output) {
output$map = renderLeaflet({
leaflet() %>% addTiles() %>%
addPolygons(data=nc, fillColor=~c('red', 'blue')[selected+1],
layerId=~FIPS)
})
observeEvent(input$map_shape_click, ignoreInit=TRUE, {
id = input$map_shape_click$id
map = leafletProxy('map') %>%
removeShape(id)
nc_local = nc
ix = which(nc_local$FIPS==id)
nc_local$selected[ix] = 1 - nc_local$selected[ix]
nc <<- nc_local
map %>% addPolygons(data=nc_local[ix,], fillColor=~c('red', 'blue')[selected+1],
layerId=id)
})
}
shinyApp(ui = ui, server = server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment