Way to add hyperlink to Leaflet popup in Shiny - r

Using leaflet in shiny to make an interactive map. Pulling data for popups from a CSV:
Row on CSV:
Name lat lng
Tufts 42.349598 -71.063541
Code on R for markers:
m %>% addMarkers(~lng, ~lat, icon = custommarker1 popup = ~htmlEscape(Name))
This returns marker in correct spot with popup displaying 'tufts'
Wondering if there is a way to encode a hyperlink into the popup directly in the CSV?Oor to put plain text as a new CSV column and have R/Shiny then turn it into a hyperlink.
Very new to shiny/leaflet and would appreciate any help!

Just include the link in the popup as html:
output$mymap <- renderLeaflet({
m <- leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addMarkers(lng=174.768, lat=-36.852, popup= ' R ')
m # Print the map
})
You can set the popup equal to a column in your dataframe as well. If your dataframe was called df and it contained longitude = long, latitude= lat, and urls = link :
output$mymap <- renderLeaflet({
m <- leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addMarkers(lng=df$long, lat=df$lat, popup= df$link)
m # Print the map
})

If you want the link to be a hyperlink, I have used this
popup = ~paste("", "click here", "")
provided your data has a column called link where the urls are.

Related

Exctracting value from a data frame using character coming from event$id in R

Some context: I want to use the layerId (as row index) from the marker a click on the leaflet map to extract another value from a data frame. The data frame is "def_veh" and has columns named "ID_Fahrzeug" and "Postleitzahl".
So I set the layerId of my markers equal to ID_Fahrzeug, so that when I observe a click on a marker the event$id returns me the value of "ID_Fahrzeug" for this marker as a character.
In the showPopup function, I would like to use this returned value to extract the value from the data frame "def_veh" that is located in the column "Postleitzahl" in the same row as the event$id value in the column "ID_Fahrzeug".
I want then to store this extracted value in the variable "codepost" to use it as input for a following function used to plot a chart.
Here is a code sample of what I tried to explain in words:
#map function
output$map <- renderLeaflet({
leaflet(def_veh) %>% #creates a map based on the coordinates of damages
addTiles() %>%
addMarkers(lng= ~Laengengrad, lat = ~Breitengrad, clusterOptions = markerClusterOptions(), layerId= ~ID_Fahrzeug) %>% #creates cluster markers to groups the points on the map where a damage occurred
setView(lng = 11.107353, lat = 50 , zoom = 7) #fits the map's boundaries on Germany (more or less)
})
# When map is clicked, show a popup with city info
showPopup <- function(id_veh, Breitengrad_OEM, Laengengrad_OEM) {
codeposte <- def_veh[def_veh$ID_Fahrzeug==id_veh,"Postleitzahl"]
Plot <- Plot_Bar_Cart(codeposte)
svg(filename= paste(folder,"plot.svg", sep = "/"),
width = 500 * 0.005, height = 300 * 0.005)
print(Plot)
dev.off()
content <- paste(popup_content,readLines(paste(folder,"plot.svg",sep="/")), collapse = "")
leafletProxy("map") %>% addPopups(Laengengrad_OEM, Breitengrad_OEM, content, layerId = ID_Fahrzeug)
}
observe({
leafletProxy("map") %>% clearPopups()
event <- input$map_marker_click
if (is.null(event))
return()
isolate({
showPopup(event$id, event$lat, event$lng)
})
})
The problem is now, that when I run my shinyApp and click on a marker on the map, the windows closes by itself... This is the error message that appears: "Error in base::try(showPopup, silent = TRUE) :
object 'showPopup' not found"
Can someone help me to locate the problem? :)

can we popop the name of the place when we use addGeoJson in R

I'm using addgeoJson function for the india map. I have data that I got it from here
https://gadm.org/download_country.html
for example I'm using this data
This is a json file and I read that json file and pass it to addGeoJson function.
library(jsonlite)
library(leaflet)
url <- "https://raw.githubusercontent.com/openseattle/seattle-boundaries/master/data/zip-codes.geojson"
geojson <- fromJSON(url, simplifyVector = FALSE)
leaflet() %>%
addTiles() %>%
addGeoJSON(geojson) %>%
setView(lng = -122.2, lat = 47.6, zoom = 10)
So I need to popup the names when I click on a particular state or city here. It should give some information when we click on it.
Is this possible to do it? and how?
The information you are looking for is stored deep in the structure of a geojson file (list). See for instance the first object of your dataset
geojson$features[[1]]$properties
Luckily there is a easier way to deal with it.
Use the package leaflet.extra, function addGeoJSONv2 specifying your label under argument popupProperty
library(leaflet.extras)
library(jsonlite)
library(leaflet)
url <- "https://raw.githubusercontent.com/openseattle/seattle-
boundaries/master/data/zip-codes.geojson"
geojson_fil <- fromJSON(url, simplifyVector = FALSE)
leaflet() %>%
addTiles() %>%
setView(lng = -122.2, lat = 47.6, zoom = 10) %>%
addGeoJSONv2(geojson_fil,
popupProperty = 'ZCTA5CE10')

Getting finer control of leaflet popups in r

I am trying to get finer control of leaflet popups in R, using the leaflet package. The code for a MWE is below:
library(dplyr)
library(magrittr)
library(leaflet)
download.file(
url = "http://biogeo.ucdavis.edu/data/gadm2.8/rds/GBR_adm1.rds",
destfile = "GBR_adm1.rds",
method = "curl"
)
shp_gbr <- readRDS("GBR_adm1.rds")
# get centroids for placing popups in second map
shp_gbr_centers <-
rgeos::gCentroid(shp_gbr, byid = TRUE) %>%
sp::SpatialPointsDataFrame(shp_gbr#data, match.ID = FALSE)
shp_gbr#data %<>%
left_join(shp_gbr_centers[1], by = 'OBJECTID', copy = TRUE) %>%
rename(lat = y, lng = x) %>%
select(NAME_1, lat, lng) %>%
mutate(text = ProgGUIinR::LoremIpsum)
popup <- paste("<b><h3>", shp_gbr$NAME_1, "</h3></b>", shp_gbr$text)
shp_gbr %>%
leaflet() %>%
addPolygons(popup = ~popup)
This gives a nice map with popups that appear on clicking within the areas of the 4 countries, but in this case, the text is too much for the popup to handle nicely:
What I would like is to access some of the popupOptions available via the addPopups function, in this case to make the popup wider and have a scroll bar. An example of this is below:
shp_gbr %>%
leaflet() %>%
addPolygons() %>%
addPopups(
data = shp_gbr#data,
popup = ~popup,
options =
popupOptions(
maxWidth = 600,
maxHeight = 100
)
)
However, the popups are now set to be open on launch, rather than appearing on clicking within the boundaries, and do not reopen on click once closed:
My question is how to combine these elements so that you could have, say, a scroll bar for too much text within a map such as the first example, where the popups are closed by default but open on click.
You could use this function to create your popup:
popup <- paste("<div class='leaflet-popup-scrolled' style='max-width:600px;max-height:100px'><b><h3>", shp_gbr$NAME_1, "</h3></b>", shp_gbr$text,"</div>")
It wraps the popup in a div with the leaflet-popup-scrolled class to add the scroll bar and inline CSS to set the max-width and max-height.

R leaflet addmarkers argument value for popup

m <- leaflet() %>%
addPolygons(data = SP) %>%
addTiles()
for(k in 1:nrow(rfcCleaned))
{
lat = rfcCleaned$Latitude[k]
long = rfcCleaned$Longitude[k]
addMarkers(m, lng, lat, popup = as.character(k))
}
m
addMarkers does not print any pop-ups. I even tried format(k) in place of as.character(k)). For the following code a single pop-up is displayed as expected. Am I doing anything wrong?
m <- leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")
m # Print the map
Thanks in advance
To add markers it is not required to bind them in loop. You can simply add them to piped command after tiles.
Here is the sample data i have used to display markers.
id slon slat
2 93.089 25.054
3 93.038 24.939
4 92.988 24.825
5 92.937 24.710
6 92.886 24.596
7 92.835 24.482
R query
library(leaflet)
ex1map<-leaflet() %>% addTiles() %>% addMarkers(ex1map, lat = ex1$slat,lng = ex1$slon,popup = as.character(ex1$id))
In the below picture i am able to see popup of their respective id.
In case if you don't want to add another column of id, here is another alternative solution.
data ex2 has records provided by you in above comments.
ex2map <- leaflet() %>% addTiles() %>% addMarkers(ex2, lat = ex2$Latitude,lng = ex2$Longitude,popup = as.character(1:nrow(ex2)))
Note: your data has duplicate records,so popups will be displayed for the last duplicate record found

How to display multiple polygons at once using leaflet addGeoJSON() function?

I am trying to display several zipcodes (thus polygons...) on a leaflet map. Data is available as a geojson file here. I chose as an example some zip codes from Seattle.
I tried the following (reproducible example):
library(jsonlite)
library(leaflet)
url <- "https://raw.githubusercontent.com/openseattle/seattle-boundaries/master/data/zip-codes.geojson"
geojson <- fromJSON(url)
map <- leaflet() %>% addTiles() %>% addGeoJSON(geojson)
map
I could not figure out how to properly set addGeoJSON parameters, and calling map only displays the leaflet() %>% addTiles() part...
Documentation is too light for the non json advanced user that I am:
geojson: a GeoJSON list, or character vector of length 1
How should I proceed? Thank you very much in advance for your views on this issue
Regards
You just needed to not parse the geojson to a data.frame, fromJSON(url, FALSE)
library(jsonlite)
library(leaflet)
url <- "https://raw.githubusercontent.com/openseattle/seattle-boundaries/master/data/zip-codes.geojson"
geojson <- fromJSON(url, simplifyVector = FALSE)
leaflet() %>%
addTiles() %>%
addGeoJSON(geojson) %>%
setView(lng = -122.2, lat = 47.6, zoom = 10)
addGeoJSON() will also accept a string, e.g.
geojson_str <- paste0(readLines(url), collapse = "")
then pass that to addGeoJSON

Resources