Created
March 22, 2018 19:42
-
-
Save kent37/63c55c0bbdb0640d8c43369cdeeebdd2 to your computer and use it in GitHub Desktop.
Leaflet map that toggles selection on click
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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