I need to create a web page that includes an interactive map where users can see popup information about data collected at many locations. Using Rstudio and leaflet on Windows, wanting to use OSM base map tiles.
My leaflet map works fine in Rstudio viewer. However, when the 'knitted' page is viewed in Firefox, no OSM map tiles appear although other components of the map are okay. Similarly OSM tiles missing in saved html widget.
I made a simple example to demonstrate.
```{r}
library(leaflet)
library(htmlwidgets)
rand_lng = function(n = 10) rnorm(n, 145.7, .01)
rand_lat = function(n = 10) rnorm(n, -17, .01)
m = leaflet() %>%
addTiles(group = "OSM (default)") %>%
addProviderTiles("Esri.WorldImagery") %>%
addCircleMarkers(rand_lng(5), rand_lat(5), group = "Points")%>%
addLayersControl(
baseGroups = c("OSM (default)","Esri.WorldImagery"),
overlayGroups = c("Points"),
options = layersControlOptions(collapsed = FALSE)) %>%
setView(lng = 145.7, lat = -17, zoom = 12)
m
saveWidget(m, "leaflet_OSMplusEsri.html")
```
This is the output I get in Rstudio viewer, with OSM tiles selected and displayed correctly. When selected, Esri tiles are correct also.
This is the html file shown in Firefox, where OSM tiles do not display despite being selected.
I've been searching all day without discovering how to troubleshoot this. As a newbie perhaps I'm missing something obvious?
I will be very grateful for advice: how to troubleshoot this problem in simple steps?
Took a long time, but I eventually resolved this. In case it helps anyone else, here is the revised version that works properly.
```{r}
library(leaflet)
library(htmlwidgets)
rand_lng = function(n = 10) rnorm(n, 145.7, .01)
rand_lat = function(n = 10) rnorm(n, -17, .01)
m = leaflet() %>%
addProviderTiles(providers$OpenStreetMap, group = "OSM") %>%
addProviderTiles(providers$Esri.WorldImagery, group = "Esri") %>%
addCircleMarkers(rand_lng(5), rand_lat(5), group = "Points")%>%
addMiniMap() %>%
addLayersControl(
baseGroups = c("OSM","Stamen", "Esri"),
overlayGroups = c("Points"),
options = layersControlOptions(collapsed = FALSE)) %>%
setView(lng = 145.7, lat = -17, zoom = 12)
m
saveWidget(m, "leaflet_OSMplusEsri.html")
```
Cause of the problem was addTiles() with default values. I'm not sure why this did not work, hoping someone might be able to explain.
Related
I found this post on stackoverflow to make an interactive map in R (second answer): Search button for Leaflet R map?
library(leaflet)
library(inlmisc)
df = read.csv(textConnection(
'Name, Lat, Long
<b>location 1</b>,42.3401, -71.0589
<b>location 2</b>,42.3501, -71.0689'))
map=leaflet(df) %>%
addTiles() %>%
setView(lng=-71.0589,lat=42.3301, zoom=12) %>%
addMarkers(~Long, ~Lat, popup = ~Name, group="marker")
map=inlmisc::AddSearchButton(map, group = "marker", zoom = 15,
textPlaceholder = "Search here")
This code works and produces a map:
But for some reason, when I try to search for one of the locations (e.g. "location 1") - the map seems to take a long time to load and experience a lot of lag. As such, I have waited several minutes and was unable to actually search for one of these cities.
Can someone please help me figure out what I am doing wrong?
Thank you!
The problem occurs when there is no label given for the locations.
library(leaflet)
library(inlmisc)
df <- read.csv(textConnection(
'Name, Lat, Long, Label,
<b>location 1</b>,42.3401, -71.0589, Loc 1
<b>location 2</b>,42.3501, -71.0689, Loc 2'))
map <- leaflet(df) %>%
addTiles() %>%
setView(lng=-71.0589,lat=42.3301, zoom=12) %>%
addMarkers(~Long, ~Lat, popup = ~Name, group="marker", label = ~Label) %>%
inlmisc::AddSearchButton(group = "marker", zoom = 15,
textPlaceholder = "Search here")
I want to make a map using leaflet so that the points in the map have popup notes. Each popup will have a clickable link to redirect to an Internet page. The URLs that will be inserted in such popups are in a column of my data frame, which has thousands of rows. Some toy data:
place <- c("a", "b", "c", "d", "e", "f")
thing <- c("potato","melon","black pepper", "bigfoot","black panther", "orchidaceae")
lat <- c(-17.456, 31.4009, 24.293, -8.956, 8.697, -25.257)
long <- c(-63.658,-111.144,-106.759,-81.029,-83.2052,-52.026)
urls <- c("https://en.wikipedia.org/wiki/Potato",
"https://en.wikipedia.org/wiki/Melon",
"https://en.wikipedia.org/wiki/Black_pepper",
"https://en.wikipedia.org/wiki/Bigfoot",
"https://en.wikipedia.org/wiki/Black_panther",
"https://en.wikipedia.org/wiki/Orchidaceae")
d <- data.frame(place, thing, lat, long, urls)
And this is the code I've been trying to use to plot the map:
library(leaflet)
library(tidyverse)
content <- paste("The", thing,
"occurs near.You can find some information",
"<b><a href=d$urls>here</a></b>")
mymap <- d %>%
leaflet() %>%
addProviderTiles(providers$Esri.WorldImagery, group = "World Imagery") %>%
addProviderTiles(providers$Stamen.TonerLite, group = "Toner Lite") %>%
addLayersControl(baseGroups =
c("Toner Lite", "World Imagery")) %>%
addMarkers(label = thing,
popup = content,
icon = ~ icons(iconUrl = "marker_red.png",
iconWidth = 28, iconHeight = 24))%>%
addMiniMap(
toggleDisplay = TRUE,
tiles = providers$Stamen.TonerLite
) %>%
print()
The problem is that the word "here" in the popup is sort of clickable, but does not redirect me to any internet page. I don't know what to do in this situation where the URLs are contained in a column of my data frame. Besides, I have no experience working with HTML objects. Could anyone help me figure out a way to pass those URLs into the popup notes?
Thanks in advance!
The problem is with href=d$urls in the content, d$urls is assigned as the URL and the actual URL is not referred here. It can be resolved using paste0 function.
The content should be
content <- paste("The", thing,
"occurs near.You can find some information",
paste0("<b>here</b>"))
mymap <- d %>%
leaflet() %>%
addProviderTiles(providers$Esri.WorldImagery, group = "World Imagery") %>%
addProviderTiles(providers$Stamen.TonerLite, group = "Toner Lite") %>%
addLayersControl(baseGroups =
c("Toner Lite", "World Imagery")) %>%
addMarkers(label = thing,
popup = content,
icon = ~ icons(iconUrl = "marker_red.png",
iconWidth = 28, iconHeight = 24))%>%
addMiniMap(
toggleDisplay = TRUE,
tiles = providers$Stamen.TonerLite
) %>%
print()
I would like to be able to add interactive shiny elements into a website. My HTML skills are not up to speed to make fancy websites from scratch. Google allows you to make nice slick well functioning websites fast, using sites.google.com.
I was wondering if it is possible to add R Shiny elements into a sites.google.com site.
For example, it is possible to put
library(plotly)
trace_0 <- rnorm(100, mean = 5)
trace_1 <- rnorm(100, mean = 0)
trace_2 <- rnorm(100, mean = -5)
x <- c(1:100)
data <- data.frame(x, trace_0, trace_1, trace_2)
p <- plot_ly(data, x = ~x, y = ~trace_0, name = 'trace 0', type = 'scatter', mode = 'lines') %>%
add_trace(y = ~trace_1, name = 'trace 1', mode = 'lines+markers') %>%
add_trace(y = ~trace_2, name = 'trace 2', mode = 'markers')
into https://sites.google.com/view/shinytest ?
EDIT: I read that in Shiny you can build a 'raw' HTML UI instead of a ShinyUI (shiny.rstudio.com/articles/html-ui.html). Would it be possible to extract the HTML from an existing site (e.g. the sites.google site from the example and keep all its functionality) and start using that as a base HTML UI in which Shiny elements can be added (and thususing the server part as back-end)?
I have a script which allows me to generate a map with with "R for leaflet" :
library(htmlwidgets)
library(raster)
library(leaflet)
# PATHS TO INPUT / OUTPUT FILES
projectPath = "path"
#imgPath = paste(projectPath,"data/cea.tif", sep = "")
#imgPath = paste(projectPath,"data/o41078a1.tif", sep = "") # bigger than standard max size (15431804 bytes is greater than maximum 4194304 bytes)
imgPath = paste(projectPath,"/test.tif", sep = "")
outPath = paste(projectPath, "/leaflethtmlgen.html", sep="")
# load raster image file
r <- raster(imgPath)
# reproject the image, if necessary
#crs(r) <- sp::CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
# color palette, which is interpolated ?
pal <- colorNumeric(c("#FF0000", "#666666", "#FFFFFF"), values(r),
na.color = "transparent")
# create the leaflet widget
m <- leaflet() %>%
addTiles() %>%
addRasterImage(r, colors=pal, opacity = 0.9, maxBytes = 123123123) %>%
addLegend(pal = pal, values = values(r), title = "Test")
# save the generated widget to html
# contains the leaflet widget AND the image.
saveWidget(m, file = outPath, selfcontained = FALSE, libdir = 'leafletwidget_libs')
My problem is that this is generating a html file and I need this map to be dyanamic. For example, when a user click on some html button which is not integrate on the map, I want to add a rectangle on the map. Any solutions would be welcome...
Leaflet itself does not provide the interactive functionality you are looking for. One solution is to use shiny, which is a web application framework for R. From simple R code, it generates a web page, and runs R on the server-side to respond to user interaction. It is well documented, has a gallery of examples, and a tutorial to get new users started.
It works well with leaflet. One of the examples on the shiny web site uses it, and also includes a link to the source code.
Update
Actually, if simple showing/hiding of elements is enough, leaflet alone will suffice with the use of groups. From the question it's not very clear how dynamic you need it to be.
I am using RStudio to create some some leaflet images.
I would like to be able to save the output as an HTML so that it can be emailed and others can view it.
Below is some sample R code which was taken from [here] to create a sample leaflet image.
devtools::install_github('rstudio/leaflet')
library(leaflet)
rand_lng = function(n = 10) rnorm(n, -93.65, .01)
rand_lat = function(n = 10) rnorm(n, 42.0285, .01)
m = leaflet() %>% addTiles() %>% addCircles(rand_lng(50), rand_lat(50), radius = runif(50, 10, 200))
m
Any code to be able to the output as HTML would be much appreciated...
Something like:
library(htmlwidgets)
saveWidget(m, file="m.html")
seems to work on most widgets.
Open a new RMarkdown document. When you are using RStudio go to File -> New File -> R Markdown.
Once you saved the file, you can insert your code into a chunk, like this:
---
title: "Leaflet Map"
output: html_document
---
```{r}
library(leaflet)
rand_lng = function(n = 10) rnorm(n, -93.65, .01)
rand_lat = function(n = 10) rnorm(n, 42.0285, .01)
m = leaflet() %>% addTiles() %>% addCircles(rand_lng(50), rand_lat(50), radius = runif(50, 10, 200))
m
```
Then Press the Knit HTML Button above the code window and your application will open in a new HTML file. You can send the file via eMail or upload it to your ftp.
I have faced the same problem and after installing Github version the problem was fixed.
# Or Github version
if (!require('devtools')) install.packages('devtools')
devtools::install_github('rstudio/leaflet')
My present version is 1.1.0.9000, running on macOS Sierra, RStudio Version 1.1.232 and R 3.4.0
You can export from RStudio or save using htmlwidgets.
Another option using mapview library is:
library(mapview)
mapshot(m, url = "m.html")
Note that you can also set the output to .png, .pdf, or .jpeg.
library(mapview)
To save as a "png" or "jpg" image:
mapshot(m, file = "m.png")
mapshot(m, file = "m.jpeg")
Even pdf can be used
Both solutions saveWidget or mapshot work correctly (saveWidget seems to be quicker), however, you should take care with color selection, especially in those choosed for borders/lines of polygons because in the stored map not all colours in borders are drawn ("grey50" for example is ignored while pure colours as "black" are drawn normally).
Curiously, these colours are stored and shown correctly when they are used as fill colour.