Last active
June 23, 2020 14:20
-
-
Save cybernar/a3cf262301e4cce3a6105ccf2e0398cc to your computer and use it in GitHub Desktop.
Shiny RStudio : Select polygon feature on a Leaflet map
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
# select polygon feature example | |
# with leaflet & shiny | |
library(shiny) | |
library(leaflet) | |
data(gadmCHE) | |
ui <- bootstrapPage( | |
tags$style(type = "text/css", "html, body {width:100%;height:100%}"), | |
leafletOutput("mymap", width = "100%", height = "100%"), | |
absolutePanel( | |
top = 10, right = 10, | |
p(strong("Click on Region")), | |
p("MAP_SHAPE_CLICK Event"), | |
verbatimTextOutput("click_on_shape"), | |
p("Selected feat. attributes"), | |
verbatimTextOutput("feat_selected") | |
) | |
) | |
server <- function(input, output, session) { | |
rv <- reactiveValues() | |
rv$selected <- NULL | |
output$mymap <- renderLeaflet({ | |
hl_opts <- highlightOptions( | |
color = "#CC0000", weight = 3, bringToFront = TRUE) | |
leaflet() %>% addTiles() %>% | |
addPolygons( | |
layerId = ~ID_1, | |
group = "cantons", | |
data = gadmCHE, | |
label = ~NAME_1, | |
fillColor = "#FCFFA4", | |
weight = 1, | |
color = "#666666", | |
opacity = 0.4, | |
fillOpacity = 0.8, | |
highlightOptions = hl_opts) %>% | |
setView(8.34, 46.77, 8) | |
}) | |
output$click_on_shape <- renderPrint({ | |
input$mymap_shape_click | |
}) | |
output$feat_selected <- renderPrint({ | |
feature <- req(rv$selected) | |
#feature_id <- feature$id | |
i <- which(gadmCHE$ID_1==feature$id) | |
as.list(gadmCHE@data[i,c("ID_1", "NAME_1", "HASC_1")]) | |
}) | |
observeEvent(input$mymap_click, { | |
new_selected <- req(input$mymap_shape_click) | |
isolate(old_selected <- rv$selected) | |
if (is.null(old_selected) || new_selected$.nonce != old_selected$.nonce) { | |
validate( | |
need(new_selected$group!="selection", message=FALSE) | |
) | |
rv$selected <- new_selected | |
i <- which(gadmCHE$ID_1==new_selected$id) | |
gadmCHE_filtered <- gadmCHE[i,] | |
leafletProxy("mymap") %>% | |
clearGroup("selection") %>% | |
addPolygons( | |
layerId = ~ID_1, | |
group = "selection", | |
data = gadmCHE_filtered, | |
fillColor = "cyan", | |
weight = 1.2, | |
color = "#666666", | |
opacity = 0.4, | |
fillOpacity = 0.8) | |
} else { | |
rv$selected <- NULL | |
leafletProxy("mymap") %>% | |
clearGroup("selection") | |
} | |
}) | |
} | |
shinyApp(ui, server) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment