I want to color map my polygons based on the user input. The column i am using has categorial variables so I am using the colorFactor function which I have tested it is functioning normally. The issue is with the observe function when I load my shiny app it terminates immediately and outputs "Error in addPolygons: unused argument (fillcolor = ~pal(AreaTyp)) in leaflet".My question is how to include reactivity correctly using the observe function. Here is my code:
#INTERACTIVE MAPPING
#colorfunction
pal<-colorFactor(rainbow(7),mp$AreaTyp)
#set data based on user input
fdata<-reactive({
data<-mp
if(input$area!="All"){
data<-data[data$AreaType==input$area,]
}
data
})
output$leaf<-renderLeaflet({
leaflet(fdata()) %>%
#Initializing the map
setView(lng=36.092245, lat=-00.292115,zoom=15)%>%
#Base map
#Add default OpenStreetMap map tiles
addTiles(group = "default")%>%
#addProviderTiles("Esri.NatGeoWorldMap",group = "default")%>%
#addProviderTiles("CartoDB.Positron",group = "custom")%>%
#Overlay map
addPolygons(
data = fdata(),
fillColor = "blue",
weight = 1, smoothFactor = 0.5,
opacity = 1.0, fillOpacity = 1.0,
group = "basepoly",
highlightOptions = highlightOptions(
weight = 2,
color = "red",
fillOpacity = 0.7,
bringToFront = TRUE
),label =~LIA
)
})
observe({
leafletProxy("leaf",data = fdata()) %>%
clearShapes() %>%
addPolygons(
weight = 1, smoothFactor = 0.5,
opacity = 1.0, fillOpacity = 1.0,
data=fdata(),
fillcolor = ~pal(AreaTyp),
label =~LIA
)
})
Change fillcolor = ~pal(AreaTyp) to fillColor = ~pal(AreaTyp)
Let's break down your error.
"Error in addPolygons: unused argument (fillcolor = ~pal(AreaTyp)) in leaflet"
first:
"Error in addPolygons:
this means that addPolygons failed to run. not that the observer failed
second
"unused argument "
This means that you added an argument that addpolygons can not use.
Third
(fillcolor = ~pal(AreaTyp)) in leaflet
This is telling you exactly which argument is wrong.
Related
I am building a Shiny app and am trying to get a resized leaflet legend using leaflegend. My dataset has several different measures in it, some that are raw counts and some percentages. I am trying to code the legend numberFormat so that it displays the appropriate format for each. I currently have the values in dat2$value and the properly formatted label in dat2$lbl. I have tried defining a function to execute this translation for numberFormat but am getting strange results.
#define getLabel
getLabel = function(x){
dat2$lbl[dat2$value == x]
}
#draw map on screen
leafletProxy("map") %>%
clearShapes() %>%
clearControls() %>%
addMapPane("polygons", zIndex = 410) %>%
addMapPane("borders", zIndex = 420) %>%
addPolygons(
data = dat2,
stroke = T,
color = "#343434",
weight = 0.5,
opacity = 1,
fillColor = ~ pal(dat2$value),
fillOpacity = 0.8,
smoothFactor = 0.2,
popup = content,
options = pathOptions(pane = "polygons")
) %>%
addLegendBin(
pal = pal,
values = dat2$value,
numberFormat = function(x) lapply(x, getLabel),
title = input$group,
position = "topleft",
orientation = "vertical"
)
Resulting output:
Any thoughts on what is going wrong here? I feel so close, but can't quite get it to where I need it to be.
I made the following map from a data frame that contains the number of parole of each state from the years 1995-2015 per 100,000 as well as the spatial information for each state. I want to incorporate it into r shiny app to have a slider to be able to choose the specific year and view it. I got the slider to work and change the data and when you first run it works and gives you the appropriate state and number. However, when you move around the slider the geospatial labels start moving around using the reactive and different states start getting different states labels. Like the following:
The slider starts at the year 2000 and as you can see the if I move it around it, in this case 2014, now we have florida being labeled as Montana.
All these was done within the R shiny app. This is the code I have below. I have my leaflet map fully created outside the server.
server <- function(input, output) {
#Set YEAR with Slider
state_parole_year <- reactive({
state_parole %>%
filter(year == year(input$year))
})
labels_year <- reactive({paste("Parole/100000 US Adults",
state_parole_year()$state, state_parole_year()$number_on_parole_per_100000_us_adult_residents)})
output$mymap <- renderLeaflet({
state_map %>%
addTiles()%>%
addPolygons(fillColor = ~ pal(state_parole_year()$number_on_parole_per_100000_us_adult_residents),
fillOpacity = 1,
color = "blue",
opacity = 0.1,
weight = 1,
highlight = highlightOptions(
weight = 3,
color = "blue",
fillOpacity = .2,
bringToFront = TRUE),
label = labels_year())
})
}
When I run the leaflet map outside of r shiny app and change the year manually by subsetting the csv it works perfectly. The problem occurs when I try to make the labels reactive to the slider. Does someone know how I can fix the problem? Thanks!
The problem is that you build the map on unfiltered data, then display it with filtered data. There is then a switch in factors.
A quick fix is to build your map on filtered data, directly in the server() function :
output$mymap <- renderLeaflet({
leaflet(data = state_parole_year()) %>%
addTiles() %>%
setView(lng = -80,
lat = 34.5,
zoom = 4) %>%
addPolygons(fillColor = ~ pal(state_parole$number_on_parole_per_100000_us_adult_residents),
fillOpacity = 1,
color = "blue",
opacity = 0.1,
weight = 1,
highlight = highlightOptions(
weight = 3,
color = "blue",
fillOpacity = .2,
bringToFront = TRUE),
label = labels) %>%
addLegend(
position = "topright",
pal = pal,
values = ~number_on_parole_per_100000_us_adult_residents,
title = "# of U.S. Adults on Parole/100000.",
opacity = 1) %>%
addTiles()%>%
addPolygons(fillColor = ~ pal(state_parole_year()$number_on_parole_per_100000_us_adult_residents),
fillOpacity = 1,
color = "blue",
opacity = 0.1,
weight = 1,
highlight = highlightOptions(
weight = 3,
color = "blue",
fillOpacity = .2,
bringToFront = TRUE),
label = ~labels_year())
})
I made a Shiny app with Year slider so that the map could update the value by Year with leafletProxy.
However, if I set fillOpacity less than 1 in addPolygons. The opacity from the next Year would overlay on the previous display. So one after one, it would fully be opaque. I could add clearShapes() after proxy %>% to overcome this, but the shape would be re-drawn and I could see the refresh.
With fillOpacity = 1, this would not be a problem, but the color is just too bright.
The first graph below is the initial view, and the second one is after sliding by one year.
Is there anyways to fix fillOpacity for each update without clearShapes()?
The parts of my codes for this are:
observe({
df <- mapSelected()
value <- as.numeric(displayValue())
proxy <- leafletProxy("mapPlot", session, data = df)
proxy %>%
addPolygons(fillColor = ~regionPal()(value), fill = TRUE,
fillOpacity = 0.6,
color = 'white', weight = 1, opacity = 0.8,
popup = paste(mapLevel(), ": ", df[[SAName()]], "<br>",
"ED counts: ", value),
highlightOptions = highlightOptions(color = 'white',
weight = 3,
opacity = 1,
bringToFront = FALSE))
})
output$mapPlot <- renderLeaflet({
leaflet() %>%
addTiles() %>%
fitBounds(lng1 = 140.99926, lng2 = 153.63873,
lat1 = -37.50508, lat2 = -28.15702)
})
Within addPolygons() there is a popup parameter just like the one in the addPopups() function. The difference (I think) is that when the popup is created within addPolygons(), one can click anywhere within the polygon to trigger the popup, but if addPopups() is used, a single lng and lat point must be defined.
I want to change one of the default options (maxWidth) in popupOptions() which can easily be done when using addPopups() because it contains the parameter options = popupOptions() but I don't know how to do it when using addPolygons(); within that function the options parameter is options = pathOptions().
Below is a reproducible example from the leaflet documentation with a popup added that I'd like increase the maxWidth.
library(rgdal)
# From https://www.census.gov/geo/maps-data/data/cbf/cbf_state.html
states <- readOGR("shp/cb_2013_us_state_20m.shp",
layer = "cb_2013_us_state_20m", verbose = FALSE)
neStates <- subset(states, states$STUSPS %in% c(
"CT","ME","MA","NH","RI","VT","NY","NJ","PA"
))
leaflet(neStates) %>%
addPolygons(
stroke = FALSE, fillOpacity = 0.5, smoothFactor = 0.5,
color = ~colorQuantile("YlOrRd", states$AWATER)(AWATER),
popup="<b>Hello World</b>"
)
You can do this simply by adding popupOptions() after your popup in the addPloygons() block like so:
leaflet(neStates) %>%
addPolygons(
stroke = FALSE, fillOpacity = 0.5, smoothFactor = 0.5,
color = ~colorQuantile("YlOrRd", states$AWATER)(AWATER),
popup="<b>Hello World</b>"
popupOptions = popupOptions(maxWidth ="100%", closeOnClick = TRUE)
)
Here is the list from the PDF vignette on leaflet R of all the things you can drop in the popupOptions() list:
popupOptions(maxWidth = 300, minWidth = 50, maxHeight = NULL,
autoPan = TRUE, keepInView = FALSE, closeButton = TRUE,
zoomAnimation = TRUE, closeOnClick = NULL, className = "", ...)
I draw a Polygon on a leafletmap which I use in a shiny app.
Everytime an event is fired I want to delete the old polygon and draw the new one over it.
That does not work - I assume I use layerId wrong?
Any hints on this?
# draw polygons
observeEvent(da$ar, {
# remove polygon
removeShape(map, layerId = unique(10))
leafletProxy("myMap") %>% addPolygons(data = da$ar, stroke = TRUE,
fillOpacity = 0.5, smoothFactor = 0.5,
layerId = unique(10)
)
})
So, I go it.
When you use a layer ID on an object and draw the same object with that layerID again, the object gets deleted.
So, that is enough:
observeEvent(da$ar, {
leafletProxy("myMap") %>% addPolygons(data = da$ar, stroke = TRUE,
fillOpacity = 0.5, smoothFactor = 0.5,
layerId = "foo"
)
})