Delete Polygon from Leafletmap R/Shiny - r

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"
)
})

Related

leafletProxy to change map with fixed fillOpacity in addPolygons, Shiny

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)
})

R Shiny Leaflet Change Labels Without Redrawing

I've been trying to change/update the popup labels based on user input. However, the map is redrawn everytime a change is made. I tried adding a delay without success. This might be a trivial question but I've been unable to solve it.
I'm using a SpaitalPolygonsDataFrame for the base data.
If I don't clearShapes(), the fillColor overwrites itself making the fillColor darker with each successive input. Any help would be appreciated.
output$map <- renderLeaflet({
leaflet(world_spdf) %>%
addTiles() %>%
setView( lat=12.97, lng=77.59 , zoom=3) %>%
addPolygons( fillColor = Data1$Color_Code, stroke=F, fillOpacity = 0.25)
})
observe({
leafletProxy("map",data = world_spdf) %>%
clearShapes() %>%
addPolygons(fillColor = Data1$Color_Code, stroke=F, fillOpacity = 0.25, popup = filteredData1(), smoothFactor = 0.2)
})

color mapping polygons based on user input

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.

Grouped layer control in Leaflet R

There is a plug-in for Leaflet JS that allows to group the layers in the layer control. https://github.com/ismyrnow/Leaflet.groupedlayercontrol
This plug-in does not seem to exist for Leaflet R but I found this post saying that there is a way to use arbitraty Leaflet JS plug-in in Leaflet R.
https://gist.github.com/jcheng5/c084a59717f18e947a17955007dc5f92
I tried to apply this method to the Leaflet.groupedlayercontrol plug-in but did not succeed. Do you have any idea how I can possibly use this plug-in or any other way to group my layers in the layercontrol generated by Leaflet R? Thank you.
You definitely can do layer control in leafletR. If you version does not have it, then you need to update, probably from the most recent GITHUB version.
I am working on a map right now that has layer controls, see the photograph. Here is the code that makes it happen. As you can see each of the addPolygons has a group = " A Name" This is where you identify the layers in the check boxes on my image.
map<-leaflet()%>%
addTiles()%>%
addPolygons(data = plotMerge,
fillColor = ~pal(plotMerge$incomePerCapita),
color = "#000000", #this is an outline color
fillOpacity = 0.8,
group="Tract",
weight = 0.2,
popup=popup)%>%
addPolygons(data = countyPoly,
fillColor = "transparent",
color = "#000000", #this is an outline color
fillOpacity = 0.8,
group="County",
popup=countyPoly#data$NAME,
weight = 2)%>%
addPolygons(data = townPoly,
fillColor = "transparent",
color = "#000000", #this is an outline color
fillOpacity = 0.8,
group="Town",
weight = .8,
popup=townPoly#data$TOWN)%>%
addPolygons(data = rphnPoly,
fillColor = "transparent",
color = "#000000", #this is an outline color
fillOpacity = 0.8,
group="Public Health Region",
weight = .8,
popup=rphnPoly#data$PHN)%>%
addLegend(pal = pal,
values = plotMerge$incomePerCapita,
position = "bottomright",
title = "State-wide Income Percentiles",
labFormat = labelFormat(digits=1))%>%
addLayersControl(
overlayGroups =c("County", "Town", "Public Health Region", "Tract"),
options = layersControlOptions(collapsed=FALSE)
)
saveWidget(map, file="map1.html", selfcontained=FALSE)
Here is what it looks like:
You can also add other controls check it out here:
Leaflet R Hidden Layers
I know this is an old question but I didn't find a good answer elsewhere - this may help others in the future.
Here is a reprex with comments that explains the code:
#load library
library(tidyverse)
library(leaflet)
#load data
data("quakes")
#map all points
# quakes %>%
# leaflet() %>%
# addProviderTiles(providers$CartoDB.Positron) %>%
# addCircleMarkers(lng = ~long, lat = ~lat, radius = 1)
#create a grouping variable -- this can be whatever you want to filter by
quakes <- quakes %>%
mutate(groups = case_when(
stations < 30 ~ 1,
stations < 50 ~ 2,
TRUE ~ 3
))
#function to plot a map with layer selection
map_layers <- function() {
#number of groups
k <- n_distinct(quakes$groups)
#base map
map <- leaflet() %>%
addProviderTiles(providers$CartoDB.Positron)
#loop through all groups and add a layer one at a time
for (i in 1:k) {
map <- map %>%
addCircleMarkers(
data = quakes %>% filter(groups == i), group = as.character(i),
lng = ~long, lat = ~lat, radius = 1
)
}
#create layer control
map %>%
addLayersControl(
overlayGroups = c(1:k),
options = layersControlOptions(collapsed = FALSE)) %>%
hideGroup(as.character(c(2:k))) #hide all groups except the 1st one
}
#plot the map
map_layers()

R Leaflet: Passing popupOptions when adding Polygons.

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 = "", ...)

Resources