How to add multiple objects to a leaflet map using Shiny - r

AIM
Create a leaflet map using Shiny that represents one set of data with circle marker and add a markers for points using a second set of data.
ISSUE
The "circle" markers are working, but "markers" are not. The "addMarkers" code is not being read or is being ignored.
SERVER
library(shiny)
library(leaflet)
server <- function(input, output, session) {
points <- read.csv(textConnection("Loc,STZip,Lat,Long,Vol
Loc1,17699,40.0185,-76.297582,15
Loc2,76177,32.949819,-97.31406,20
Loc3,27801,35.935125,-77.77076,17
Loc4,52404,41.947335,-91.68819,12
Loc5,19380,39.983108,-75.59332,18
"))
newpoints <- read.csv(textConnection("Loc,STZip,Lat,Long,Vol
Loc6,18640,41.317242,-75.77942,12
Loc7,38133,35.208709,-89.80518,20
"))
output$mymap <- renderLeaflet({
leaflet() %>%
addProviderTiles("Stamen.TonerLite",
options = providerTileOptions(noWrap = TRUE)) %>%
addCircleMarkers(lng = ~Long, lat = ~Lat, radius = ~Vol, layerId = NULL,
group = "NGS_Facilities", stroke = TRUE, color = "#0000CC", weight = 5, opacity = 0.5,
fill = TRUE, fillColor = "#0000CC", fillOpacity = 0.2, dashArray = NULL,
popup = ~Loc, options = pathOptions(), clusterOptions = NULL, clusterId = NULL,
data = (newpoints)) %>%
#this code is not being read or is ignored...
addMarkers(lng = ~Long, lat = ~Lat, popup = ~Loc, data = (newpoints))
})
}
UI
library(shiny)
library(leaflet)
r_colors <- rgb(t(col2rgb(colors()) / 255))
names(r_colors) <- colors()
ui <- fluidPage(
title = "Map of Stuff",
leafletOutput("mymap", width = 1800, height = 800),
p()
)

This is a weird error... fought with it for a while, until I realized it was a problem with how you read your data.
> newpoints
Loc STZip Lat Long Vol
1 Loc6 18640 41.31724 -75.77942 12
2 Loc7 38133 35.20871 -89.80518 20
3 NA NA NA NA
Because your end quote is on a new line, it leaves a break. This causes the last line in your data to be NAs. When I was debugging, it seemed like anything I put before the data would display, but after would fail.
To fix this, read your data as:
points <- read.csv(textConnection("Loc,STZip,Lat,Long,Vol
Loc1,17699,40.0185,-76.297582,15
Loc2,76177,32.949819,-97.31406,20
Loc3,27801,35.935125,-77.77076,17
Loc4,52404,41.947335,-91.68819,12
Loc5,19380,39.983108,-75.59332,18"))
newpoints <- read.csv(textConnection("Loc,STZip,Lat,Long,Vol
Loc6,18640,40.0185,-76.297582,12
Loc7,38133,35.208709,-89.80518,20"))
For whatever reason, Leaflet bugs out if the last row is all NAs

Related

R - shiny - addPolygons must be called with both lng and lat, or with neither

I would like to ask for some help here.
I have my polygon shapefile and I would like to display it trough leaflet in R-shiny. However, I keep having the result: Error: addPolygons must be called with both lng and lat, or with neither.
I already tried with sp package and sf package (following whit link: https://community.rstudio.com/t/projection-problems-with-leaflet/27747/5), and changed the CRS also with both packages. Outside from shiny it works fine, but inside of it is just not working.
library(rgdal)
library(sp)
library(leaflet)
wo <-readOGR("SHAPES/world/ne_50m_admin_0_countries.shp", layer = "ne_50m_admin_0_countries")
wt <- spTransform(wo, CRS("+proj=longlat +init=epsg:4326 +ellps=WGS84 +datum=WGS84 +no_defs"))
ui <- fluidPage(
# Application title
titlePanel("mytitle"),
mainPanel(
leafletOutput("map", width = "100%", height = 600)
)
)
)
server <- function(input, output) {
output$map <- renderLeaflet({
leaflet(wt) %>%
addTiles(group = "OpenStreetMap") %>%
addProviderTiles("CartoDB.Positron", group = "CartoDB")%>%
addProviderTiles("Esri.WorldImagery", group = "ESRI")%>%
setView(lng= -78.49511705 , lat = -1.47200601, zoom = 5)%>%
addMiniMap(tiles = providers$CartoDB.Positron,
toggleDisplay = TRUE) %>%
addLayersControl(baseGroups = c("OpenstreetMap", "CartoDB", "ESRI"))%>%
addPolygons(color = "white", weight = 1, smoothFactor = 0.5,
opacity = 1,0, fillOpacity = 0.5
#dashArray = "3",
#highlightOptions = highlightOptions(color = "grey", weight =2,
#bringToFront = TRUE)
)
})
}
# Run the application
shinyApp(ui = ui, server = server)
I also tried to display the variable inside the addPolygons, like this:
addPolygons(data = wt, color = "white", weight = 1, smoothFactor = 0.5,
opacity = 1,0, fillOpacity = 0.5
#dashArray = "3",
#highlightOptions = highlightOptions(color = "grey", weight =2,
#bringToFront = TRUE)
)
Could somebody give any glimpse of what is happening here, please
In the addPolygons instead of data = wt , try using data = wt ().

R Shiny Leaflet - how to make a CheckboxGroup for binary data

I posted a similar question here:
How do I create a Leaflet Proxy in observeEvent() for checkboxGroup in R Shiny .
But I'm a little desperate for answers, so I thought I'd rephrase my question and post it again. I've scoured the internet for answers and can't seem to find what I'm looking for. Apologies for the double posting.
Here's my issue.
I have a dataset here:
https://github.com/mallen011/Leaflet_and_Shiny/blob/master/Shiny%20Leaflet%20Map/csv/RE.csv
It's recycling centers in Kentucky. It's set up so each recyclable material is a column, and each row i.e. recycling center is listed as yes/no as to whether each center actually recycles said material.
Here's an example of what the data looks like, in case you can't access the csv. Top row is the header column. Sorry for the formatting:
Name___________________GL______AL_____PL
Bath Community Recycling___Yes_____No____Yes
Ted & Sons Scrap Yard______No______No____Yes
Now I have the csv visualized on a R shiny dashboard app like here using Leaflet:
https://github.com/mallen011/Leaflet_and_Shiny/blob/master/Shiny%20Leaflet%20Map/re_map.png
But I want to add a control in which users can filter through where they can recycle their goods, namely, I want to use checkboxGroupInput() in R shiny so users can check materials and have recycling centers populate the map. For example, if a person wants to know where to recycle their glass, they can check "glass" in the checkbox group, and all recycling centers that allow glass recycling pop up.
So in R Shiny, I've read my recycling data csv (RE.csv):
RE <- read.csv("C:/Users/username/Desktop/GIS/Shiny Leaflet Map/csv/RE.csv")
RE$y <- as.numeric(RE$y)
RE$x <- as.numeric(RE$x)
RE.SP <- SpatialPointsDataFrame(RE[,c(7,8)], RE[,-c(7,8)])
Here's my UI that puts the checkboxGroupInput() in the sidebar():
ui <- dashboardPage(
skin = "blue",
dashboardHeader(titleWidth = 400, title = "Controls"),
dashboardSidebar(width = 400
#here's the checkboxgroup, it calls the columns for glass, aluminum and plastic from the RE.csv, all of which have binary values of yes/no
checkboxGroupInput(inputId = "RE_check",
label = h3("Recycleables"),
choices = list("Glass" = RE$GL, "Aluminum" = RE$AL, "Plastic" = RE$PL),
selected = 0)
),
dashboardBody(
fluidRow(box(width = 12, leafletOutput(outputId = "map"))),
tags$style(type = "text/css", "#map {height: calc(100vh - 80px) !important;}"),
leafletOutput("map")
)
)
And now for the trouble I'm having: What do I put into my server so it observes each of these events?
This is what I have for the event in which a user checks "glass", and I have no idea how wrong or how right it is. I just know it's not working. I'm trying to use "if" statements, so only values that equal "yes" populate the map. But currently, the map in the dashboard is blank no matter what I do, although the checkbox group input seems to work.
server <- function(session, input, output) {
observeEvent({
RE_click <- input$map_marker_click
if (is.null(RE_click))
return()
if(input$RE$GL == "Yes"){
leafletProxy("map") %>%
clearMarkers() %>%
addMarkers(data = RE_click,
lat = RE$y,
lng = RE$x)
return("map")
}
})
Here's my output leaflet map too, in case that matters:
output$map <- renderLeaflet({
leaflet() %>%
setView(lng = -83.5, lat = 37.6, zoom = 8.5) %>%
addProviderTiles("Esri.WorldImagery") %>%
addProviderTiles(providers$Stamen.Toner, group = "Toner") %>%
addPolygons(data = counties,
color = "green",
weight = 1,
fillOpacity = .1,
highlight = highlightOptions(
weight = 3,
color = "green",
fillOpacity = .3)) %>%
addMarkers(data = RE,
lng = ~x, lat = ~y,
label = lapply(RE$popup, HTML),
group = "recycle",
clusterOptions = markerClusterOptions(showCoverageOnHover = FALSE)) %>%
addLayersControl(baseGroups = c("Esri.WorldImagery", "Toner"),
overlayGroups = c("recycle"),
options = layersControlOptions(collapsed = FALSE))
})
}
I'm new to R Shiny if that's not obvious. I'd really appreciate any and all help.
All my code is publicly available on my GitHub for download:
https://github.com/mallen011/Leaflet_and_Shiny
Thanks and stay safe!
Maybe this would work... You can add the different recycle types as layers, then add the checkboxes on the leaflet map instead of worrying about shiny integration. Obviously, you'd have to add the rest of your recycle types on here...
library(leaflet)
library(htmlTable)
RE <- read.csv("https://raw.githubusercontent.com/mallen011/Leaflet_and_Shiny/master/Shiny%20Leaflet%20Map/csv/RE.csv")
leaflet() %>%
setView(lng = -83.5, lat = 37.6, zoom = 8.5) %>%
addProviderTiles("Esri.WorldImagery") %>%
addProviderTiles(providers$Stamen.Toner, group = "Toner") %>%
# addPolygons(data = counties,
# color = "green",
# weight = 1,
# fillOpacity = .1,
# highlight = highlightOptions(
# weight = 3,
# color = "green",
# fillOpacity = .3)) %>%
addMarkers(data = RE[RE$AL=="Yes", ],
lng = ~x, lat = ~y,
#label = lapply(RE$popup, HTML),
group = "AL",
clusterOptions = markerClusterOptions(showCoverageOnHover = FALSE)) %>%
addMarkers(data = RE[RE$FE=="Yes", ],
lng = ~x, lat = ~y,
#label = lapply(RE$popup, HTML),
group = "FE",
clusterOptions = markerClusterOptions(showCoverageOnHover = FALSE)) %>%
addMarkers(data = RE[RE$NONFE=="Yes", ],
lng = ~x, lat = ~y,
#label = lapply(RE$popup, HTML),
group = "NONFE",
clusterOptions = markerClusterOptions(showCoverageOnHover = FALSE)) %>%
addLayersControl(baseGroups = c("Esri.WorldImagery", "Toner"),
overlayGroups = c("AL", "FE", "NONFE"),
options = layersControlOptions(collapsed = FALSE))

Rshiny : displaying chart when clicking on a polygon

I'm a Rshiny newbie very eager to learn but right now I'm facing an issue I cannot overcome alone and I would greatly appreciate if someone could help me out ! :)
My problem is (I guess) quite simple:
I have created a map with my polygons and I've managed to display some basic informations when I click on them (have a look on here) but I have no idea how to add a barplot (for example) below my map for each polygon I click.
Could someone help me on how doing that please ? (after hours and hours of attempts my eyesballs are really about to pop out of their sockets !!!)
Many thanks in advance !
Romain
My code:
library(shiny)
library(leaflet)
library(dplyr)
library(magrittr)
library(devtools)
library(RColorBrewer)
library(rgdal)
library(sp)
communes <- readOGR("G:/Ateliers/Projet/communes.shp")
commmunes#data
nom_commune INSEE Variable_1 Variable_2 Variable_3 area_sqkm
1 AUZEVILLE-TOLOSANE 31035 289 8.727212 9.336384 6.979758
2 CASTANET-TOLOSAN 31113 85 4.384877 8.891650 8.460724
3 LABEGE 31254 288 5.047406 2.031651 7.663404
4 PECHBUSQUE 31411 443 6.577743 8.120896 3.099422
5 RAMONVILLE-SAINT-AGNE 31446 95 2.601305 8.909278 6.236784
>
ui <- fluidPage(
leafletOutput("mymap"))
#### SERVEUR R #####
bins <- c(3,3.5,6,6.5,7,7.5,8,8.5)
pal <- colorBin("YlOrRd", domain = communes$area_sqkm, bins = bins)
labels <- sprintf(
"<strong>%s</strong><br/>%g km2",
communes$nom_commun, communes$area_sqkm
) %>% lapply(htmltools::HTML)
server <- function(input, output, session) {
output$mymap<-renderLeaflet(
leaflet(communes) %>%
addProviderTiles(providers$Stamen.TonerLite,
options = providerTileOptions(noWrap = TRUE)
) %>%
setView(1.50, 43.54, zoom = 12) %>%
addTiles() %>%
addPolygons(fillColor = ~pal(area_sqkm),
weight = 2,
opacity = 1,
color = "white",
dashArray = "3",
fillOpacity = 0.7,
highlight = highlightOptions(
weight = 5,
color = "#666",
dashArray = "",
fillOpacity = 0.7,
bringToFront = TRUE),
label = labels,
labelOptions = labelOptions(
style = list("font-weight" = "normal", padding = "3px 8px"),
textsize = "15px",
direction = "auto")) %>%
addLegend(pal = pal, values = ~area_sqkm, opacity = 0.7, title = NULL,
position = "bottomright")
)
}
shinyApp(ui = ui, server=server)
The data I would like to display in my barplots are the variable 1,2 and 3 :
data <- read.csv("G:/Ateliers/Projet/communes.csv", sep=";")
data
nom_commune INSEE Variable_1 Variable_2 Variable_3 area_sqkm
1 AUZEVILLE-TOLOSANE 31035 289 8.727212 9.336384 6.979758
2 CASTANET-TOLOSAN 31113 85 4.384877 8.891650 8.460724
3 LABEGE 31254 288 5.047406 2.031651 7.663404
4 PECHBUSQUE 31411 443 6.577743 8.120896 3.099422
5 RAMONVILLE-SAINT-AGNE 31446 95 2.601305 8.909278 6.236784
>
Here is an example shiny app with other data, since I do not have access to your shape data for the map. I believe this might do what you need it to do and can be adapted for your needs.
I would create a reactiveVal to store the id of the polygon region that is clicked on (this variable stores input$mymap_shape_click$id). You data used in addPolygons should have an id to reference.
In your plot (or in a separate reactive expression), you can filter the data based on the reactiveVal containing the id.
library(shiny)
library(leaflet)
library(rgdal)
library(sf)
library(ggplot2)
library(tidyverse)
arcgis_data = st_read("http://data.phl.opendata.arcgis.com/datasets/bc2b2e8e356742568e43b0128c344d03_0.geojson")
arcgis_data$id <- 1:nrow(arcgis_data) ## Add an 'id' value to each shape
plot_data <- read.table(text =
"id nom_commune INSEE Variable_1 Variable_2 Variable_3 area_sqkm
1 AUZEVILLE-TOLOSANE 31035 289 8.727212 9.336384 6.979758
2 CASTANET-TOLOSAN 31113 85 4.384877 8.891650 8.460724
3 LABEGE 31254 288 5.047406 2.031651 7.663404
4 PECHBUSQUE 31411 443 6.577743 8.120896 3.099422
5 RAMONVILLE-SAINT-AGNE 31446 95 2.601305 8.909278 6.236784", header = T, stringsAsFactors = F
)
ui <- fluidPage(
leafletOutput(outputId = "mymap"),
plotOutput(outputId = "myplot")
)
server <- function(input, output){
## use reactive value to store the id from observing the shape click
rv <- reactiveVal()
output$mymap <- renderLeaflet({
leaflet() %>%
addPolygons(data = arcgis_data %>% slice(1:5), layerId = ~id) %>%
addProviderTiles("CartoDB.Positron")
})
observeEvent(input$mymap_shape_click, {
rv(input$mymap_shape_click$id)
})
## you can now plot your plot based on the id of region selected
output$myplot <- renderPlot({
plot_data %>%
filter(id == rv()) %>%
pivot_longer(cols = starts_with("Variable"), names_to = "Variable", values_to = "Value") %>%
ggplot(aes(x = Variable, y = Value)) +
geom_col()
})
}
shinyApp(ui, server)
Edit: For your uploaded data, you don't need to add a separate id for communes. Instead, you could match by name (nom_commune). You can use that in your layerId instead. This looks like it should work. I did take out some of the additional label information as this appeared to be missing from the .shp file I downloaded.
library(shiny)
library(leaflet)
library(rgdal)
library(sf)
library(ggplot2)
library(tidyverse)
communes <- readOGR("communes_ok.shp")
ui <- fluidPage(
leafletOutput(outputId = "mymap"),
plotOutput(outputId = "myplot")
)
server <- function(input, output){
## use reactive values to store the id from observing the shape click
rv <- reactiveVal()
output$mymap<-renderLeaflet(
leaflet(communes) %>%
addProviderTiles(providers$Stamen.TonerLite,
options = providerTileOptions(noWrap = TRUE)) %>%
setView(1.50, 43.54, zoom = 12) %>%
addTiles() %>%
addPolygons(fillColor = "blue",
weight = 2,
opacity = 1,
color = "white",
dashArray = "3",
fillOpacity = 0.3,
highlight = highlightOptions(
weight = 5,
color = "#666",
dashArray = "",
fillOpacity = 0.7,
bringToFront = TRUE),
layerId = ~nm_cmmn)
)
observeEvent(input$mymap_shape_click, {
rv(input$mymap_shape_click$id)
})
## you can now 'output' your generated data however you want
output$myplot <- renderPlot({
if (is.null(rv())) return (NULL)
plot_data %>%
filter(nom_commune == rv()) %>%
pivot_longer(cols = starts_with("Variable"), names_to = "Variable", values_to = "Value") %>%
ggplot(aes(x = Variable, y = Value)) +
geom_col()
})
}
shinyApp(ui, server)

How to create a leaflet choropleth map of US counties

With the code below I get my dataframe with US county data
library(raster)
library(leaflet)
library(tidyverse)
# Get USA polygon data
USA <- getData("GADM", country = "usa", level = 2)
### Get data
mydata <- read.csv("https://www.betydb.org/miscanthus_county_avg_yield.csv",
stringsAsFactors = FALSE)
My object is to crate an interactive leaflet choropleth map of Avg_yield so first I fortify my USA polygon data
library(rgeos)
library(maptools)
library(ggplot2)
states.shp.f <- fortify(USA, region = "NAME_2")
Then I subset my dataset and merge it with the fortified:
mydata2<-mydata[,c("COUNTY_NAME","Avg_yield")]
colnames(mydata2)[1]<-"id"
## merge shape file with data
merge.shp.coef <- merge(states.shp.f, mydata2, by = "id")
but now I have a dataset with every county name many times and also some counties have different values of Avg_yield. Whats the proper way to process those data in order to use the leaflet code like:
leaflet() %>%
addProviderTiles("OpenStreetMap.Mapnik") %>%
setView(lat = 39.8283, lng = -98.5795, zoom = 4) %>%
addPolygons(data = USA, stroke = FALSE, smoothFactor = 0.2, fillOpacity = 0.3,
fillColor = ~mypal(mydata$Avg_yield),
popup = paste("Region: ", USA$NAME_2, "<br>",
"Avg_yield: ", mydata$Avg_yield, "<br>")) %>%
addLegend(position = "bottomleft", pal = mypal, values = mydata$Avg_yield,
title = "Avg_yield",
opacity = 1)
The propoer way to do this is to transform your polygon object into a sf object
with st_as_sf()
Here you have a working example :
(I did used some other data for the polygon, I thought yours too precise and require a lot of resources, plus I made it work with shiny)
library(leaflet)
library(tidyverse)
library(ggplot2)
library(sf)
library(shiny)
USA <- st_read(dsn = '[your path]/cb_2018_us_county_500k.shp')
### Get data
mydata <- read.csv("https://www.betydb.org/miscanthus_county_avg_yield.csv",
stringsAsFactors = FALSE)
states_sf <- st_as_sf(USA)
mydata2<-mydata[,c("COUNTY_NAME","Avg_yield")]
colnames(mydata2)[1]<-"NAME"
## merge shape file with data
states_sf_coef <- left_join(states_sf, mydata2, by = "NAME")
ui <- fluidPage(
leafletOutput("map", height = "100vh")
)
server <- function(input, output, session) {
bins <- c(0, 5, 10, 15, 20, 25, 30, 35, 40)
mypal <- colorBin("YlOrRd", domain = states_sf_coef$Avg_yield, bins = bins)
#Sortie map
output$map <- renderLeaflet({
leaflet()%>%
addProviderTiles("OpenStreetMap.Mapnik")%>%
setView(lat = 39.8283, lng = -98.5795, zoom = 4) %>%
addPolygons(
data = states_sf_coef,
fillColor = ~mypal(states_sf_coef$Avg_yield),
stroke = FALSE,
smoothFactor = 0.2,
fillOpacity = 0.3,
popup = paste("Region: ", states_sf_coef$NAME_2, "<br>",
"Avg_yield: ", states_sf_coef$Avg_yield, "<br>"))%>%
addLegend(position = "bottomleft",
pal = mypal,
values = states_sf_coef$Avg_yield,
title = "Avg_yield",
opacity = 1)
})
}
# Create Shiny app ----
shinyApp(ui = ui, server = server)

R Shiny addPolygons fails in leafletproxy but works in leaflet()

I am trying to create a leaflet map that adds and removes a polygon layer (SpatialDataFrame) based on changing user inputs into a flexdashboard Shiny App. The geometry of the polygons (4201 polygons) remains constant, but as user makes changes to inputs, the data set (2100500 records total) that merges with each polygon changes (to =4201 to merge with polygons).
I've been following the Leaflet R docs here https://rstudio.github.io/leaflet/shiny.html
And my sample code below seems to mimic the observe() event recommend to wrap around the addPolygons(). I've also looked at the source code from a number of similar Shiny apps from the shiny gallery page (particularly this one: https://walkerke.shinyapps.io/neighborhood_diversity/) but it doesn't seem to work
Here is a sample of the app, note the data are too large to load but see the comments. When I create the addPolygons() in the first leaflet() call, it works fine. The downside of this approach is that it causes the entire map to redraw when user input changes. Following leaflet documentation suggestion I then want to move this addPolygon into a separate observer. This is where it fails.
---
title: "Model Result Viewer"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
runtime: shiny
---
```{r setup, include=FALSE}
library(flexdashboard)
library(...)
df <- fread("./data/rca_do_salt_1day.csv")
# get the unique parameters & layers
model_params <- unique(df$Parameter)
model_layers <- unique(df$Cell_K)
# read in the grid
grid <- spTransform(readOGR(dsn="./PVSC06_Grid", layer="PVSC06_WGS84"),
CRS("+proj=longlat +datum=WGS84 +no_defs"))
# Data Controls --------------------------------
<USER INPUTS SIMILAR TO:
# parameter selection
selectInput("param", "Parameter", model_params, selected = model_params[1])
#layer selection
selectInput("lyr", "Layer", model_layers, selected = model_layers[1])
# make the grid dataframe
df_subset <- reactive({
filter(df, Cell_K == input$lyr, Parameter == input$param, Time == input$timeslider)
})
# THIS MAKES THE POLYGONS FOR MAPPING
sp.grid <- reactive({
merge(grid, df_subset(), by.x = "Id", by.y = "Id")
})
# helpers for leaflet
pal <- reactive({
colorNumeric(
palette = input$colors, #"YlOrRd",
domain = df_parameter()$Value
)
})
#Set labels for grid hover
labels <- reactive({
sp.grid()$Value %>% lapply(htmltools::HTML)
})
output$map <- renderLeaflet({
leaflet() %>%
# Base Setup
addTiles(group = "Open Street Map") %>%
addProviderTiles('Esri.WorldImagery', group = "Satellite Imagery") %>%
addDrawToolbar(
targetGroup='Draw',
editOptions = editToolbarOptions(selectedPathOptions = selectedPathOptions())
) %>%
clearShapes() %>%
fitBounds(grid#bbox[1], grid#bbox[2], grid#bbox[3], grid#bbox[4]) %>%
# ================ THIS WORKS HERE, BUT NOT IN AN OBSERVER?!!! =================
# addPolygons(data = sp.grid(),
# layerId = ~Id,
# group= "Grid",
# weight = 0.1,
# opacity = 0,
# fillOpacity = 1,
# stroke = FALSE,
# fillColor = ~pal()(Value),
# highlightOptions = highlightOptions(color = "white",
# weight = 2,
# bringToFront = TRUE),
# label = labels(),
# labelOptions = labelOptions(style = list("font-weight" = "normal", padding = "3px 8px"),
# textsize = "15px",
# direction = "auto")) %>%
# # Legend
# addLegend(position = 'bottomright',
# pal = pal(), opacity = 1,
# values = sp.grid()$Value,
# title = input$param) %>%
#==================================================================================
# TOC Box
addLayersControl(
baseGroups = c("Satellite Imagery", "Open Street Map"),
overlayGroups = c("Grid", "Loads", "Draw"),
options = layersControlOptions(collapsed=TRUE)
)
})
# =============== THIS DOESN"T WORK ======================
observe({
req(sp.grid()) # this alone will cause the error
# why doesn't this work?
leafletProxy('map', data = sp.grid()) %>%
removeShape(~Id) %>%
addPolygons(
layerId = ~Id,
group= "Grid",
weight = 0.1,
opacity = 0,
fillOpacity = 1,
fill = TRUE,
stroke = FALSE,
fillColor = ~pal()(Value),
highlightOptions = highlightOptions(color = "white",
weight = 2,
bringToFront = TRUE),
label = labels(),
labelOptions = labelOptions(style = list("font-weight" = "normal", padding = "3px 8px"),
textsize = "15px",
direction = "auto")
)
})
# === THIS IS JUST EXAMPLE OF Observer that DOES work?!
# Click event for the map (will use to generate chart)
click_element <- eventReactive(input$map_shape_click, {
input$map_shape_click$id
})
# highlight the clicked element
observe({
req(click_element()) # do this if click_element() is not null
# Add the clicked element to the map in aqua, and remove when a new one is clicked
map <- leafletProxy('map') %>%
removeShape('element') %>%
addPolygons(data = sp.grid()[sp.grid()$Id == click_element(), ],
fill = TRUE,
color = '#00ffff', opacity = 1, layerId = 'element')
})
leafletOutput('map')
When I run this code, the Rmarkdown console gives error of something like and immediately crashes:
Error in : Result must have length 2100500, not 0
90 <Anonymous>
Note the actual number (90) varies but it is usually always >85 and it is the only line output in the Rmarkdown console.
Noteworthy: The 2100500 is the number of records in my non-spatial dataframe (that is filtered by user inputs and merged with spatial polygon (4201 polygons).
Therefore, it looks like the filtering isn't applying correctly, but then how come this works when i simply move it into the leaflet() call?

Resources