Search code examples
rshinyr-leaflet

Shiny Leaflet - Highlight polygon


I have a simple shiny-app with just a dropdown listing districts of Afghanistan and a leaflet map of the same. enter image description here

The shape file can be accessed at this link - using AFG_adm2.shp from http://www.gadm.org/download

here's the app code:

library(shiny)
library(leaflet)
library(rgdal)
library(sp)

afg <- readOGR(dsn = "data", layer ="AFG_adm2", verbose = FALSE, stringsAsFactors = FALSE)

ui <- fluidPage(
    titlePanel("Test App"),
    selectInput("yours", choices = c("",afg$NAME_2), label = "Select Country:"),
    leafletOutput("mymap")

)

server <- function(input, output){
  output$mymap <- renderLeaflet({
    leaflet(afg) %>% #addTiles() %>%
       addPolylines(stroke=TRUE, color = "#00000", weight = 1) 
  })
}

# Run the application 
shinyApp(ui = ui, server = server)

I want the functionality that when I select a district from the dropdown list, the border fill of that district changes, and the setView function brings that district into focus. Can someone help me out with the code? I've looked at this post but can't make much sense of it.


Solution

  • You could use leafletProxy to change the map when the user selects a district. You can add a slightly thicker red polygon on top of the one previously drawn to highlight it and use setView to move the view around.

    This is what I would add:

    proxy <- leafletProxy("mymap")
    
      observe({
        if(input$yours!=""){
          #get the selected polygon and extract the label point 
          selected_polygon <- subset(afg,afg$NAME_2==input$yours)
          polygon_labelPt <- selected_polygon@polygons[[1]]@labpt
    
          #remove any previously highlighted polygon
          proxy %>% removeShape("highlighted_polygon")
    
          #center the view on the polygon 
          proxy %>% setView(lng=polygon_labelPt[1],lat=polygon_labelPt[2],zoom=7)
    
          #add a slightly thicker red polygon on top of the selected one
          proxy %>% addPolylines(stroke=TRUE, weight = 2,color="red",data=selected_polygon,group="highlighted_polygon")
        }
      })
    }