Creating label in leaflet map using htmltools produces tiny label - html

Creating a leaflet map. First step, specify the label. The code used on leaflet github puts
%>% lapply(htmltool::HTML)
after the sprintf() function. However, making it is creating the label as a type:"list" resulting in the error: "Error in sum(sapply(label, function(x) { : invalid 'type' (list) of argument"
So to try and get around this I just load the htmltools library and use the code
HTML(sprintf(...))
Doing this works and runs the map, however, the labels show up as small boxes with no information (see picture link below)
I can't tell if this is something to do with the code inside sprintf() or if this has to do with HTML().
The weird thing is that the %>% lapply method was working just fine, but something happened and now its giving the error mentioned above
Image with the small label shown as little white box
labels.dest2 <- sprintf("<div style = 'overflow-wrap: anywhere;'><strong>%s <br/>%s Destinations</div><br/>%s Euclidean Miles from LAX on average<br/>%s minutes between OD tweets </div><br/>%s Miles from LAX on average</div><br/>%s minutes from LAX on average</div>",
puma.spdf$NAME,
puma.spdf$Dest_pt_count,
puma.spdf$Avg_Euc_Dist_Mi,
puma.spdf$Avg_tweetTime,
puma.spdf$Avg_RtDist_Mi,
puma.spdf$Avg_RtTime_min) %>% lapply(htmltools::HTML)
leaflet() %>% addTiles() %>% etc...
FULL CODE HERE
## Map with OD data and travel stats ##
labels.dest2 <- HTML(sprintf("<div style = 'overflow-wrap: anywhere;'> <strong>%s <br/>%g Destinations</div><br/>%s Euclidean Miles from LAX on average<br/>%s minutes between OD tweets </div><br/>%s Miles from LAX on average</div><br/>%s minutes from LAX on average</div>",
puma.spdf$NAME,
puma.spdf$Dest_pt_count,
puma.spdf$Avg_Euc_Dist_Mi,
puma.spdf$Avg_tweetTime,
puma.spdf$Avg_RtDist_Mi,
puma.spdf$Avg_RtTime_min))
leaflet() %>% addTiles() %>%
setView(lng=-118.243683, lat=34.1, zoom = 9.35) %>%
addEasyButton(easyButton(
icon="fa-crosshairs", title = "Default View",
onClick=JS("function(btn, map) {var groupLayer = map.layerManager.getLayerGroup('Destinations (red)'); map.fitBounds(groupLayer.getBounds());}"))) %>%
addProviderTiles(providers$CartoDB.Positron,
group = "Grey") %>%
addProviderTiles(providers$OpenStreetMap.BlackAndWhite,
group = "OSM") %>%
# Add Polygons
# Destination data
addPolygons(data = puma.spdf,
group = "Destination Density",
fillColor = ~pal.dest(Dest_pt_count),
weight = 1,
opacity = 90,
color = "white",
dashArray = "3",
fillOpacity = 0.5,
highlight = highlightOptions(weight = 2,
color = "#666",
dashArray = "",
fillOpacity = 0.7,
bringToFront = TRUE,
sendToBack = TRUE),
label = labels.dest2,
labelOptions = labelOptions(style = list("font-weight" = "normal", padding = "3px 8px"),
textsize = "15px",
direction = "auto")) %>%
addLegend(values=puma.spdf$Dest_pt_count,
group = "Destination Density",
pal=pal.dest,
title="Destination Density (Dest per PUMA)",
position = "bottomright") %>%
# Add Points
addCircleMarkers(data = D.spdf,
radius = 2,
color = "red",
group = "Destinations (red)",
fillOpacity = 0.5) %>%
addCircleMarkers(data = O.spdf,
radius = 2,
color = "green",
group = "Origins (green)") %>%
# Add Layer Controls
addLayersControl(
baseGroups = c("OSM (default)", "Grey"),
overlayGroups = c("Destinations (red)", "Origins (green)","Destination Density"),
options = layersControlOptions(collapsed = FALSE)
)

The problem was that the first column puma.spdf$NAME was not part of the dataset and was throwing off the string.. check to make sure all the variables you want to show are actually part of the dataset.

Related

Several lines with different style in Caption in both html and docx - flextable

I need to show data caption, computer name and period in the header of table.
I have also requirements: zebra theme, merging cells if needed. That's why I chose flextable.
Here is my code:
library(officer) # border settings library
library(flextable) # drawing tables library
library(dplyr)
Caption <- "<b><big>Computer01.domain.com</big></b><br>Network Interface<br>Gbit Total/sec<br><small>2021-05-14 18:04 to 2021-05-25 13:29</small>"
bold_border <- fp_border(color="gray", width =2)
std_border <- fp_border(color="gray")
stub <- "2021-05-14 01:40 to 2021-05-17 08:26"
table_data <- data.frame (
Instance = c("Intel[R] Ethernet 10G",
"Intel[R] Ethernet Converged Network Adapter _1",
"Intel[R] Ethernet Converged Network Adapter _2",
"Intel[R] Ethernet 10G",
"Intel[R] Gigabit"),
Max = c(2.45, 2.41, 2.29, 2.17, 0),
Avg = c(0.15, 0.15, 0.15, 0.17, 0)
)
table <- table_data %>% flextable() %>%
set_caption(caption = Caption , html_escape = F) %>%
bg(bg = "#579FAD", part = "header") %>%
color(color = "white", part = "header") %>%
theme_zebra(
odd_header = "#579FAD",
odd_body = "#E0EFF4",
even_header = "transparent",
even_body = "transparent"
) %>%
set_table_properties(width = 1, layout = "autofit") %>%
hline(part="all", border = std_border ) %>%
vline(part="all", border = std_border ) %>%
border_outer( border = bold_border, part = "all" ) %>%
fix_border_issues() %>%
set_header_labels(
values = list(Instance = InstanceName ) ) %>%
flextable::font (part = "all" , fontname = "Calibri")
save_as_docx( table, path = file.path("c:\\temp", "test01.docx") )
save_as_html (table, path = file.path("c:\\temp", "test01.html"))
Here is what I got in html which is okay for me:
But in docx format my header style is not applied:
How can I create header like I did for html that can be saved to both html and docx?
If I have to create separate tables - one for html, other for docx - it's not so good but acceptable options. That case my question how to create header I made in html but for docx format?

R: saving multiple html widgets together

I am using the R programming language. I am interested in learning how to save several "html widgets" together. I have been able to manually create different types of html widgets:
#widget 1
library(htmlwidgets)
library(leaflet)
library(RColorBrewer)
# create map data
map_data <- data.frame(
"Lati" = c(43.6426, 43.6424, 43.6544, 43.6452, 43.6629), "Longi" = c(-79.3871, -79.3860, -79.3807, -79.3806, -79.3957),
"Job" = c("Economist", "Economist", "Teacher", "Teacher", "Lawyer"),
"First_Name" = c("John", "James", "Jack", "Jason", "Jim"),
"Last_Name" = c("Smith", "Charles", "Henry", "David", "Robert"),
"vehicle" = c("car", "van", "car", "none", "car")
)
kingdom <- c("Economist", "Lawyer", "Teacher")
my_palette <- brewer.pal(3, "Paired")
factpal <- colorFactor(my_palette, levels = kingdom)
groups <- unique(map_data$Job)
# finalize map
map <- leaflet(map_data) %>%
addTiles(group = "OpenStreetMap") %>%
addCircleMarkers(~Longi, ~Lati, popup = ~Job,
radius = 10, weight = 2, opacity = 1, color = ~factpal(Job),
fill = TRUE, fillOpacity = 1, group = ~Job
)
widget_1 = map %>%
addLayersControl(overlayGroups = groups, options = layersControlOptions(collapsed = FALSE)) %>%
addTiles() %>%
addMarkers(lng = ~Longi,
lat = ~Lati,
popup = ~paste("Job", Job, "<br>",
"First_Name:", First_Name, "<br>",
"Last_Name:", Last_Name, "<br>", "vehicle:", vehicle, "<br>"))
widget 2:
##### widget 2
library(plotly)
library(ggplot2)
p_plot <- data.frame(frequency = c(rnorm(31, 1), rnorm(31)),
is_consumed = factor(round(runif(62))))
p2 <- p_plot %>%
ggplot(aes(frequency, fill = is_consumed)) +
geom_density(alpha = 0.5)
widget_2 = ggplotly(p2)
widget 3:
#####widget_3
today <- Sys.Date()
tm <- seq(0, 600, by = 10)
x <- today - tm
y <- rnorm(length(x))
widget_3 <- plot_ly(x = ~x, y = ~y, mode = 'lines', text = paste(tm, "days from today"))
widget 4:
####widget_4
library(igraph)
library(dplyr)
library(visNetwork)
Data_I_Have <- data.frame(
"Node_A" = c("John", "John", "John", "Peter", "Peter", "Peter", "Tim", "Kevin", "Adam", "Adam", "Xavier"),
"Node_B" = c("Claude", "Peter", "Tim", "Tim", "Claude", "Henry", "Kevin", "Claude", "Tim", "Henry", "Claude")
)
graph_file <- data.frame(Data_I_Have$Node_A, Data_I_Have$Node_B)
colnames(graph_file) <- c("Data_I_Have$Node_A", "Data_I_Have$Node_B")
graph <- graph.data.frame(graph_file, directed=F)
graph <- simplify(graph)
nodes <- data.frame(id = V(graph)$name, title = V(graph)$name)
nodes <- nodes[order(nodes$id, decreasing = F),]
edges <- get.data.frame(graph, what="edges")[1:2]
widget_4 = visNetwork(nodes, edges) %>% visIgraphLayout(layout = "layout_with_fr") %>%
visOptions(highlightNearest = TRUE, nodesIdSelection = TRUE)
From here, I found another stackoverflow post where a similar question was asked: Using R and plot.ly, how to save multiples htmlwidgets to my html?
In this post, it explains how to save several html widgets together - the person who answered the question wrote a function to do so:
library(htmltools)
save_tags <- function (tags, file, selfcontained = F, libdir = "./lib")
{
if (is.null(libdir)) {
libdir <- paste(tools::file_path_sans_ext(basename(file)),
"_files", sep = "")
}
htmltools::save_html(tags, file = file, libdir = libdir)
if (selfcontained) {
if (!htmlwidgets:::pandoc_available()) {
stop("Saving a widget with selfcontained = TRUE requires pandoc. For details see:\n",
"https://github.com/rstudio/rmarkdown/blob/master/PANDOC.md")
}
htmlwidgets:::pandoc_self_contained_html(file, file)
unlink(libdir, recursive = TRUE)
}
return(htmltools::tags$iframe(src= file, height = "400px", width = "100%", style="border:0;"))
}
I tried using this function to save the 4 widgets together:
save_tags(widget_1, widget_2, widget_3, widget_4)
But doing so, I got the following error:
Error in dirname(file) : a character vector argument expected
Is there a straightforward and simple way for saving multiple html widgets together?
Thanks
NOTE: I know that you can use the combineWidgets() function in R:
library(manipulateWidget)
combineWidgets(widget_1, widget_2, widget_3, widget_4)
However, I am working with a computer that has no internet access or USB ports. This computer has a pre-installed copy of R with limited libraries (it has all the libraries used throughout my question except "manipulateWidget"). I am looking for the simplest way to save multiple html widgets together (e.g. is this possible in base R)?
Thanks
If format doesn't matter too much, you can merge the widgets using tagList and save them directly:
htmltools::save_html(tagList(widget_1, widget_2, widget_3, widget_4), file = "C://Users//Me//Desktop//widgets.html")
(It goes without saying that you will need to edit the filepath!)
If you want to control the layout of the widgets, you can wrap each in a div, and then style those:
doc <- htmltools::tagList(
div(widget_1, style = "float:left;width:50%;"),
div(widget_2,style = "float:left;width:50%;"),
div(widget_3, style = "float:left;width:50%;"),
div(widget_4, style = "float:left;width:50%;")
)
htmltools::save_html(html = doc, file = "C://Users//Me//Desktop//widgets.html")

Post local image into a popup using leaflet and R

I've been trying like crazy to add local images (as in image files in my computer) into my leaflet map using R. I have plotted around 500 coordinates analyzing some images and I wish to show that specific image when clicking (popup).
leaflet(pics) %>%
addTiles() %>%
addCircleMarkers(
fillOpacity = 0.8, radius = 5,
lng = ~GPSLongitude, lat =~GPSLatitude,
color = ~pal(Married),
popup = ~SourceFile, # WISH TO ADD EMBEDDED LOCAL IMAGE IN HERE
label = mapply(function(x, y) {
HTML(sprintf("<em>%s</em></br> %s", htmlEscape(x), htmlEscape(y)))},
pics$Address, pics$DateTimeOriginal, SIMPLIFY = F),
labelOptions = lapply(1:nrow(pics), function(x) {
labelOptions(direction='auto')
}))
I am attaching 2 screenshots: one hovering the mouse and the other one clicking on a specific place. Ideally, I'd wish to show the image and the image file name when I click on each one. Is that possible?
I can also show you an RPub with the example: http://rpubs.com/laresbernardo/photomap
Hope you can help me. Thanks!
_________________________ UPDATE _________________________
All code used for this example. Basically I scan for all images with geotags, bring the address to add on a label and then plot all coordinates. When I click on a coordinate I wish to see that picture.
wd <- "/Users/bernardo/Dropbox (Personal)/Documentos/R/R Mapping/GPS Photos"
# ------------------------------------------- get the pics with geotags
library(exifr)
library(dplyr)
library(lubridate)
library(beepr)
library(maps)
time <- Sys.time(); print(time)
setwd("/Users/bernardo/Dropbox (Personal)/Imágenes")
files <- list.files(pattern = "*.jpg|*.JPG|*.png|*.PNG", recursive=T)
exif <- read_exif(files, tags = c("SourceFile", "DateTimeOriginal", "GPSLongitude", "GPSLatitude"))
pics <- exif %>% filter(!is.na(GPSLongitude)) %>%
mutate(DateTimeOriginal = ymd_hms(DateTimeOriginal))
pics$Owner <- ifelse(grepl("iPhone Maru", pics$SourceFile), "Maru", "Ber")
pics$Married <- ifelse(as.Date(pics$DateTimeOriginal) >= '2016-04-30', TRUE, FALSE)
pics$Country <- maps::map.where(database="world", pics$GPSLongitude, pics$GPSLatitude)
#lares::freqs(pics %>% filter(!is.na(Country)), Country)
# Save pics with geotags
setwd(wd)
write.csv(pics, "with_geotags.csv", row.names = F)
print(Sys.time() - time)
beepr::beep()
# ------------------------------------------- get the addresses from files
# GET ALL ADDRESSES
library(ggmap)
options(warn=-1)
setwd(wd)
pics <- read.csv("with_geotags.csv")
addresses <- read.csv("with_address.csv")
pics_to_search <- pics %>% filter(!SourceFile %in% addresses$SourceFile)
print(paste0("Without address: ",round(100 * nrow(pics_to_search)/nrow(pics), 2),"% | ", nrow(pics_to_search)))
out <- data.frame()
for (i in 1:nrow(pics_to_search)) {
Address <- revgeocode(cbind(pics_to_search$GPSLongitude, pics_to_search$GPSLatitude)[i,], output="address")[1]
if (!is.na(Address)) {
out <- rbind(out, cbind(SourceFile=as.character(pics_to_search$SourceFile[i]), Address))
print(paste(i, Address, sep=" - "))
}
}
# Save pics with geotags
pics_with_address <- rbind(out, addresses)
write.csv(pics_with_address, "with_address.csv", row.names = F)
# ------------------------------------------- Map all coordinates with leaflet
setwd(wd)
library(leaflet)
library(htmltools)
library(mapview)
pics <- read.csv("with_geotags.csv")
address <- read.csv("with_address.csv")
pal <- colorFactor(c("green4", "navy"), domain = c(FALSE, TRUE))
pics <- left_join(pics, address, by=c("SourceFile"))
pics$Content <- paste("Dirección:","<em>", pics$Address,"</em>", "<br/> Fecha:", as.Date(pics$DateTimeOriginal))
leaflet(pics) %>%
addTiles() %>%
addCircleMarkers(
fillOpacity = 0.8, radius = 5,
lng = ~GPSLongitude, lat =~GPSLatitude,
color = ~pal(Married),
popup = popupImage(as.character(pics$SourceFile), src = "local"),
label = mapply(function(x, y) {
HTML(sprintf("<em>%s</em></br> %s", htmlEscape(x), htmlEscape(y)))},
pics$Address, pics$DateTimeOriginal, SIMPLIFY = F),
labelOptions = lapply(1:nrow(pics), function(x) {
labelOptions(direction='auto')
}))
But...
I even installed the latest version with devtools::install_github("r-spatial/mapview#develop")
With no reproducible example it is hard, but takes this for instance:
library(leaflet)
library(mapview)
# make-up dataset
data_df <- data.frame(lat = as.numeric(c("35.68705", "35.88705")), long = as.numeric(c("51.38", "53.35")))
# Loaded random pictures on my laptop
images <- c("/PathToImage1/download.jpeg",
"/PathToImage2/download1.jpeg")
leaflet(data_df) %>%
addTiles() %>%
addCircleMarkers(
fillOpacity = 0.8, radius = 5,
lng = ~long, lat =~lat,
popup = popupImage(images)
)
Click on each point to see a different image. Make sure to load your images in the same order as your data frame.
Finally after lots of hours wasted in this problem, I managed to fix the issue. Thanks to #MLavoie and #TimSalabim3 (via Twitter) for the support.
This was it: if you are running macOS, you should have installed a driver called gdal. I literally just installed it, ran the original script and it worked. Don't know what that gdal does but it really did the job!

labels in leaflet r with HTML tags

All good souls, help needed. I am creating a leaflet map and cannot resolve a strange issue with labels. I created labels with few variables and the labels render ok if the first variable is numeric, but they fail if the first is a string - any idea what's the issue?
Let's start with a dummy spdf:
library(htmltools)
library(sp)
library(leaflet)
df <- new("SpatialPointsDataFrame", data = structure(list(PMID = c(184397, 184397), SPACEID = c("184397_1", "184397_2")), .Names = c("PMID", "SPACEID"), row.names = 1:2, class = "data.frame"), coords.nrs = numeric(0), coords = structure(c(-0.14463936, -0.14468822, 51.50726534, 51.50730171), .Dim = c(2L, 2L), .Dimnames = list(c("1", "2"), c("x", "y"))), bbox = structure(c(-0.14468822, 51.50726534, -0.14463936, 51.50730171), .Dim = c(2L, 2L), .Dimnames = list(c("x", "y"), c("min", "max"))), proj4string = new("CRS", projargs = "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
now we (m)apply a simple HTML line (the original used the df rows but it is not needed and can be simplified to
df#data$HT<-mapply(function(x,y){htmltools::HTML(sprintf("<h2>%s</h2> %s",x,y))},1,"L", SIMPLIFY = F)
and this one will work fine. But if the order is reversed - instead of (1,"L") we change to ("L",1) - it fails:
df#data$HT<-mapply(function(x,y){htmltools::HTML(sprintf("<h2>%s</h2> %s",x,y))},"L",1, SIMPLIFY = F)
in the first case the map contains correct labels and in the other one it produces empty label
leaflet() %>%
addTiles() %>%
addMarkers(data = df, label = ~ HT)
if I use label = ~as.character(HT) it shall produce a verbatim HTML tag, but not the label. What's wrong with it?
After playing around the code, I found that replacing mapply() with map2() in the purrr package does the trick here. I am not totally sure why this is the case. Both Slav and I confirmed that this solution is working on our machines.
library(sp)
library(leaflet)
library(htmltools)
library(purrr)
df#data$HT1 <- map2(1, "L", ~htmltools::HTML(sprintf("<h2>%s</h2> %s",.x,.y)))
df#data$HT2 <- map2("L", 1, ~htmltools::HTML(sprintf("<h2>%s</h2> %s",.x,.y)))
leaflet()%>%
addProviderTiles("OpenStreetMap.Mapnik") %>%
addLabelOnlyMarkers(data = df, label = ~HT2,
labelOptions = labelOptions(noHide = TRUE, direction = 'center',
textOnly = FALSE, textsize = "15px"))

htmlwidgets side by side in html?

Say I have two htmlwidgets
# Load energy projection data
# Load energy projection data
library(networkD3)
URL <- paste0(
"https://cdn.rawgit.com/christophergandrud/networkD3/",
"master/JSONdata/energy.json")
Energy <- jsonlite::fromJSON(URL)
# Plot
sankeyNetwork(Links = Energy$links, Nodes = Energy$nodes, Source = "source",
Target = "target", Value = "value", NodeID = "name",
units = "TWh", fontSize = 12, nodeWidth = 30)
and
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))
And I want to put them side by side in an html page. How can I do this? Could I use an iframe? Other?
There are lots of ways to answer this. Often sizing and positioning will vary based on who authored the htmlwidget, so you might need to experiment a little. The easiest way if you don't plan to use a CSS framework with grid helpers will be to wrap each htmlwidget in tags$div() and use CSS. You also might be interested in the very nice new flexbox-based dashboard package from RStudio http://github.com/rstudio/flexdashboard.
# Load energy projection data
# Load energy projection data
library(networkD3)
URL <- paste0(
"https://cdn.rawgit.com/christophergandrud/networkD3/",
"master/JSONdata/energy.json")
Energy <- jsonlite::fromJSON(URL)
# Plot
sn <- sankeyNetwork(Links = Energy$links, Nodes = Energy$nodes, Source = "source",
Target = "target", Value = "value", NodeID = "name",
units = "TWh", fontSize = 12, nodeWidth = 30,
width = "100%")
library(leaflet)
data(quakes)
# Show first 20 rows from the `quakes` dataset
leaf <- leaflet(data = quakes[1:20,]) %>% addTiles() %>%
addMarkers(~long, ~lat, popup = ~as.character(mag))
library(htmltools)
browsable(
tagList(list(
tags$div(
style = 'width:50%;display:block;float:left;',
sn
),
tags$div(
style = 'width:50%;display:block;float:left;',
leaf
)
))
)