Leaflet for R clear raster with shiny - r

I'm wondering if their is a way to clear a raster image with shiny when the user click on some radio button. I saw there is a function to clear polygons - clearshape() but I need to do the same with my raster image.
leafletProxy("map", data = filteredData()) %>%
addRasterImage(r, colors=pal, opacity = 0.9, maxBytes = 123123123) %>%
clearShapes()
This does not work...

clearImages() can be used to replace or remove rasters - https://rdrr.io/cran/leaflet/man/remove.html:
leafletProxy("map", data = filteredData()) %>%
addRasterImage(r, colors=pal, opacity = 0.9, maxBytes = 123123123) %>%
clearImages()

Related

Converting Values using numberFormat in leaflegend on Shiny

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.

Creating a heatmap on R using leaflet function add_heatmap() or addHeatmap()

I am trying to create a plot with heatmap using plotly add_heatmap() function, but it generates an error message saying Error: Must supply z attribute I referred to this site for addHeatmap() function provided by leaflet.extras package.
The following code only displays dots from addCircles() and outputs a warning message and a map as shown below:
final_df %>%
leaflet() %>%
addTiles() %>%
addCircles(
lng = final_df$long,
lat = final_df$lat,
popup = final_df$station_name
) %>% addHeatmap(lng = final_df$long, lat = final_df$lat, radius=5)
I have tried a different function add_heatmap() from leaflet which does not display any maps and generates an error.
final_df %>%
leaflet() %>%
addTiles() %>%
addCircles(
lng = final_df$long,
lat = final_df$lat,
popup = final_df$station_name
) %>% add_heatmap(lng = final_df$long, lat = final_df$lat)
Anyone faced a similar issue and created a heatmap on R?
Remove addCircles part and try:
library(leaflet.extras)
final_df %>%
leaflet() %>%
addTiles() %>%
addHeatmap(lng = final_df$long, lat = final_df$lat, blur = 40, max = 0.05, radius = 15)

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

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

Change color of leaflet marker

Is there anyway to change the color of leaflet marker base on the value of some variable. In the following map, for example, I wish to assign marker color based on mag variable:
library(leaflet)
data(quakes)
# Show first 20 rows from the `quakes` dataset
leaflet(data = quakes[1:20,]) %>% addTiles() %>%
addMarkers(~long, ~lat, popup = ~as.character(mag))
I often use the circle markers because you can change both the size and color based on other variables. For example, I have created a binned variable from a continuous using the following code:
# first cut the continuous variable into bins
# these bins are now factors
last$BeatHomeLvl <- cut(last$BeatHome,
c(0,.5,1,2,3,5,100), include.lowest = T,
labels = c('<.5x', '.5-1x', '1-2x', '2-3x', '3-5x','5x+'))
# then assign a palette to this using colorFactor
# in this case it goes from red for the smaller values to yellow and green
# standard stoplight for bad, good, and best
beatCol <- colorFactor(palette = 'RdYlGn', last$BeatHomeLvl)
When you plot it, I use the code for circle markers. The radius/area of the circle is based on the actual value of the factor and then color is assigned according to the bins.
m1 <- leaflet() %>%
addTiles() %>%
addProviderTiles(providers$OpenStreetMap, group = 'Open SM') %>%
addProviderTiles(providers$Stamen.Toner, group = 'Toner') %>%
addProviderTiles(providers$Esri.NatGeoWorldMap, group = 'NG World') %>%
setView(lng = -72, lat = 41, zoom = 8) %>%
addCircleMarkers(data = Jun, lat = ~Lat, lng = ~Lon,
color = ~beatCol(BeatHomeLvl), popup = Jun$Popup,
radius = ~sqrt(BeatHome*50), group = 'Home - Jun') %>%
At the end of your code add a legend. I added some formatting.
addLegend('bottomright', pal = beatCol, values = last$BeatHomeLvl,
title = 'Compare Home<br>Quote Count to<br>3Mos State Avg',
opacity = 1)
This gives you color-coded and sized circles based on a variable and a nice legend.
As far as I know, you need to assign an image file to one level of icon. For instance, if you have three levels in magnitude in the earthquake data, you need to create an icon list with three image paths. Then, you can have three different colors in markers. At least, the following example is getting closer to what you want. I edited a png file and created three png files. You need to specify the paths of the file when you make an icon list.
library(dplyr)
library(leaflet)
mutate(quakes, group = cut(mag, breaks = c(0, 5, 6, Inf), labels = c("blue", "green", "orange"))) -> mydf
### I edit this png file and created my own marker.
### https://raw.githubusercontent.com/lvoogdt/Leaflet.awesome-markers/master/dist/images/markers-soft.png
quakeIcons <- iconList(blue = makeIcon("/Users/jazzurro/Documents/Stack Overflow/blue.png", iconWidth = 24, iconHeight =32),
green = makeIcon("/Users/jazzurro/Documents/Stack Overflow/green.png", iconWidth = 24, iconHeight =32),
orange = makeIcon("/Users/jazzurro/Documents/Stack Overflow/orange.png", iconWidth = 24, iconHeight =32))
leaflet(data = mydf[1:100,]) %>%
addTiles() %>%
addMarkers(icon = ~quakeIcons[group])
This one worked for me:
Source: https://github.com/bhaskarvk/leaflet/blob/master/inst/examples/awesomeMarkers.R
library(leaflet)
icon.glyphicon <- makeAwesomeIcon(icon= 'flag', markerColor = 'blue', iconColor = 'black')
icon.fa <- makeAwesomeIcon(icon = 'flag', markerColor = 'red', library='fa', iconColor = 'black')
icon.ion <- makeAwesomeIcon(icon = 'home', markerColor = 'green', library='ion')
# Marker + Label
leaflet() %>% addTiles() %>%
addAwesomeMarkers(
lng=-118.456554, lat=34.078039,
label='This is a label',
icon = icon.glyphicon)
leaflet() %>% addTiles() %>%
addAwesomeMarkers(
lng=-118.456554, lat=34.078039,
label='This is a label',
icon = icon.fa)
leaflet() %>% addTiles() %>%
addAwesomeMarkers(
lng=-118.456554, lat=34.078039,
label='This is a label',
icon = icon.ion)
# Marker + Static Label using custom label options
leaflet() %>% addTiles() %>%
addAwesomeMarkers(
lng=-118.456554, lat=34.078039,
label='This is a static label',
labelOptions = labelOptions(noHide = T),
icon = icon.fa)
Why not use vector markers based on svg (here is one example implementation - https://github.com/hiasinho/Leaflet.vector-markers) that you can apply any fill color you want to? Instead of having to create a large amount of static image files. Some code involved, yes, but a lot more flexible.
L.Marker uses images (one for the marker, one for the shadow) so that's not possible. You can however use your own images, there's a good write up on the topic among the tutorials on the Leaflet site:
http://leafletjs.com/examples/custom-icons.html

Resources