Sorry guys, i have hit a brick wall here and since i am not a programmer i am not sure how to explain this either
Basically have a Shapefile with thousands of records and each record represents a document (PDF/TIF files).. I am able to subset the shapefile to specific areas of interest then i have a column for the hyperlink to a unique file for that record. I am using a popup function so that when i click i see that box with the path to the file, but i cannot get it to appear as a hyperlink.. Doing tests i can successful add in hyperlinks for websites, but i really need these hyperlinks based on the field from the table e.g. BLR_25K$Hyperlink, just have no idea changing the string to a hyperlink to the document.
Please can anyone help? Can offer something in return!
Thanks
m <- leaflet() %>%
addTiles() %>%
setView (lng=40.479, lat=52.179, zoom = 3) %>%
addPolygons(data = BLR_25K, color = "#0058cc", weight = 1, smoothFactor = 0.5, popup = "<a href = BLR_25K$Hyperlink>Product </a>", group = "Belarus 25K", label = lapply(BLR_25K$label, HTML)) %>%
enter code hereaddLayersControl(overlayGroups = c("Belarus 25K"),
options = layersControlOptions(collapsed = TRUE))
m
I think in your case, you want to use paste to add your hyperlink from BLR_25K$Hyperlink along with tags for the popup argument.
For example, you could try:
popup = paste0("<a href = '", BLR_25K$Hyperlink, "'>Product</a>")
Here is full demo of a world map to illustrate, with credit to this answer. This will include popup links to wikipedia for each country.
library(leaflet)
library(sf)
download.file(url = "http://thematicmapping.org/downloads/TM_WORLD_BORDERS_SIMPL-0.3.zip",
destfile = "TM_WORLD_BORDERS_SIMPL-0.3.zip")
unzip(zipfile = "TM_WORLD_BORDERS_SIMPL-0.3.zip")
world.borders <- read_sf(dsn = getwd(), layer = "TM_WORLD_BORDERS_SIMPL-0.3")
world.borders$wiki <- paste0("https://en.wikipedia.org/wiki/", world.borders$NAME)
leaflet() %>%
addTiles() %>%
setView(lng = 40.479, lat = 52.179, zoom = 3) %>%
addPolygons(data = world.borders,
color = "#0058cc",
weight = 1,
smoothFactor = 0.5,
popup = paste0(
"<b>Country: </b>"
, world.borders$NAME
, "<br>"
, "<a href='"
, world.borders$wiki
, "'>Click Here to View Wiki</a>"
),
label = ~NAME
)
Related
I'm trying to add separate images to popups so that as you click on each location, an image specific to that place/popup appears. I've figured out how to get one image in, but it applies to all of the popups on the map instead of just one. I have been trying to use the package leafpop for this, but I can't really figure out how to make it work. Even if I just use one image, nothing appears on the map.
This is what my code looks like for it:
library(leaflet)
library(leafpop)
img = system.file("file/image_name.jpg", package = "jpg")
leaflet(map) %>%
addTiles() %>%
addCircleMarkers(label = map#data$name,
weight = 2,
color = "grey",
fillColor = "red",
fillOpacity = 0.7)%>%
addPopupImages(img, group = "map")
I know there's some bits in there that I'm not quite doing right. At this point, I just want to know if it's even possible to do this the way I'm envisioning. Any help is appreciated.
The images need to be in a vector of the same length as the points passed to leaflet. Here is a reproducible example you can copy paste that will get you started:
library(tidyverse)
library(sf)
library(leaflet)
library(leafpop)
pts <- tibble(x = runif(10, 175, 176),
y = runif(10, -38, -37)) %>%
st_as_sf(coords = c("x", "y"), crs = 4326)
img <- glue::glue("https://github.com/IQAndreas/sample-images/blob/gh-pages/100-100-color/{11:20}.jpg?raw=true")
pts$img <- img
leaflet() %>%
addTiles() %>%
addCircleMarkers(data = pts, group = "pts") %>%
addPopupImages(pts$img, group = "pts")
Figured it out, with the help of Rich Pauloo! This is the code I ended up using the get local image files. It's a little clunky, but it worked out for me:
data_name <- readOGR("data/map_file.kml")
data_name2 <- data.frame(data_name)
pts <- st_as_sf(data.frame(data_name2),
coords = c("coords.x1", "coords.x2"), crs = 4326)
img <- c("images/picture_name.jpg") ##did this for every image I wanted to use, in the order
##that matched up with the data points I wanted them associated with.
pts$img <- img
leaflet() %>%
addTiles() %>%
addCircleMarkers(data = pts, group = "pts") %>%
addPopupImages(pts$img, group = "pts", width = 300)
Sorry if my conventions for writing out code are not quite right for the website. I just wanted to keep things generic and not include any of my file names or anything.
Anyone created a leaflet map in Code Workbook using r-Leaflet? I have a functioning script that runs (also double checked in R) but how do I get it to visualise and then use in a Report etc. I have tried various tweaks on what may get it to run but no success - any ideas
leaflet_map <- function(map_data) {
library(leaflet)
data<-map_data
# first cut the continuous variable into bins
# these bins are now factors
data$Fill_rateLvl <- cut(data$Fill_rate,
c(0,.5,0.6,0.7,0.8,0.9,1), include.lowest = T,
labels = c('<50%', '50-60%', '60-70%', '70-80%', '80-90%','90-100%'))
# 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
FillCol <- colorFactor(palette = 'RdYlGn', data$Fill_rateLvl)
m<-leaflet() %>%
addTiles() %>%
addProviderTiles(providers$CartoDB.Positron)%>%
setView(lng = -0, lat = 50, zoom = 8) %>%
addCircleMarkers(data = data, lat = ~lat, lng = ~long,
color = ~FillCol(Fill_rateLvl), popup = data$Lead_employer,
radius = ~sqrt(Fill_rate*50), group = 'Fill rate') %>%
addLegend('bottomright', pal = FillCol, values = data$Fill_rateLvl,
title = 'Fill rate for next two weeks',
opacity = 1)
return(NULL)
}
I am not familiar with R in code workbook, but it sounds to me that you need to materialize your leaflet map as a dataset and then consume it in some sort of map compatible UI.
For example slate has a map widget which is backed by leaflets. You can find documentation and examples for it in https://www.palantir.com/docs/foundry/slate/widgets-map/
Currently, I have a shiny application that creates a leaflet map of species points. When you hover over a point, the species name is displayed both as a label and a popup.
leafletProxy("map", data = filteredData()) %>%
clearMarkers() %>%
addCircleMarkers(popup = ~as.character(species),
label = ~as.character(species),
radius = 6,
stroke = TRUE,
weight = 1,
fillOpacity = 5,
fillColor = ~pal(species),
color = "black")
I have read up on how to add an image to a popup, but this would add the same image to all popups. What I would like to happen is once a point is clicked, a popup appears with the name of the species and a picture (either local file or web-linked, whichever is easiest)- So that each group (species) would have its own associated picture.
Is this possible?
Yes, if you want to each group to have its own image, you need to create a new column which contains URL to your image. And the important part is to use HTML img tag in popup.
See demo below.
data <- data.frame(
lng = c(-1,0,1,2),
lat = c(-1,0,1,2),
label = c("p1","p2","p3","p4"),
# some random images I picked up from google images
# it can be both local or remote
image_link = c(
"https://jessehouwing.net/content/images/size/w2000/2018/07/stackoverflow-1.png",
"https://store-images.s-microsoft.com/image/apps.18496.14408192455588579.aafb3426-654c-4eb2-b7f4-43639bdd3d75.2c522ca4-9686-4ee2-a4ac-cdbfaf92c618?mode=scale&q=90&h=1080&w=1920",
"https://mk0jobadderjftub56m0.kinstacdn.com/wp-content/uploads/stackoverflow.com-300.jpg",
# row number 4 use the same link as row number 1
"https://mk0jobadderjftub56m0.kinstacdn.com/wp-content/uploads/stackoverflow.com-300.jpg"
)
)
library(leaflet)
leaflet(data = data) %>%
addTiles() %>%
addCircleMarkers(
lng = ~lng,
lat = ~lat,
popup = ~paste0(
"<img src='",image_link,"' width='50px' height='50px'>"
)
)
You could also replicate code from here:
https://github.com/abenedetti/bioNPS
I made a map of London using https://data.london.gov.uk/dataset/statistical-gis-boundary-files-london and shiny and R and leaflet. I added an attribute to the shapefile, and now want to be able to highlight the shapefile and print information when the user clicks on a specific polygon.
I looked at shiny leaflet ploygon click event, Marker mouse click event in R leaflet for shiny, and How to implement input$map_marker_click correctly?, and know I need to use ObserveEvent, but have not been able to implement it correctly.
My code is:
library(shiny)
library("rgdal")
library(leaflet)
shapeData <- readOGR('statistical-gis-boundaries-london/ESRI/LSOA_2004_London_Low_Resolution.shp')
shapeData <- spTransform(shapeData, CRS("+proj=longlat +ellps=GRS80"))
shapeData$col=sample(c('red','yellow','green'),nrow(shapeData),1) #add some value you want to map
borough=read.csv('BoroughCentres.csv')
ui=fluidPage(
fluidPage(
leafletOutput('LSOAMap'),
p(),
selectInput('LANAME','Borough',
choices = unique(shapeData$LA_NAME))
)
)
server=function(input, output) {
output$LSOAMap <- renderLeaflet({
llong=borough[borough$Borough==input$LANAME,3]
llat=borough[borough$Borough==input$LANAME,4]
bor=subset(shapeData,shapeData$LA_NAME %in% input$LANAME)
leaflet() %>% addTiles() %>%
setView(lng = llong, lat=llat,zoom=13) %>%
addPolygons(data=bor,weight=2,col = 'black',fillOpacity = 0.2,fillColor = bor$col,
highlightOptions = highlightOptions(color='white',weight=1,
bringToFront = TRUE)) %>%
addMarkers(lng = llong,lat=llat,popup=input$LANAME)
})
}
shinyApp(ui, server)
I tried adding, along with session as an argument:
observe({
click <- input$map_marker_click
if (is.null(click))
return()
print(click)
text <-
paste("Lattitude ",
click$lat,
"Longtitude ",
click$lng)
leafletProxy(mapId = "LSOAMap") %>%
clearPopups() %>%
addPopups(dat = click, lat = ~lat, lng = ~lng, popup = text)
# map$clearPopups()
# map$showPopup(click$latitude, click$longtitude, text)
})
to no avail.
What I want is that when a user highlights a specific shape, text pops up and shows the corresponding STWARDNAME from the shapefile.
the first few lines of borough are:
> head(borough)
Borough LA_CODE long lat
1 City of London E09000001 -0.09194991 51.51814
2 Barking and Dagenham E09000002 0.13064556 51.54764
3 Barnet E09000003 -0.20416711 51.61086
4 Bexley E09000004 0.13459320 51.45981
5 Brent E09000005 -0.26187070 51.55697
6 Bromley E09000006 0.03734663 51.38836
You are pretty close but have a few syntax issues which I think are tripping you up.
First you are not properly selecting what STWARDNAME you want from your SPDF so there is no way for R to know which one to show. I added this line
popup = subset(shapeData, LA_NAME == input$LANAME )$STWARDNAME
Also you were passing highlightOptions as an option when it should just be highlight
Finally since you were more interested in mouseover for a polygon, I removed the popup marker and changed to highlight so that the name is shown when you mouseover the polygon:
leaflet() %>% addTiles() %>%
setView(lng = llong, lat=llat,zoom=13) %>%
addPolygons(data=bor,weight=2,col = 'black',fillOpacity = 0.2,fillColor = bor$col,
highlight = highlightOptions(color='white',weight=1,
bringToFront = TRUE), label= popup)
Which yields:
#Stedy answer was brilliant, and better, I just went a different way. I added in a layer id vector, and a popup decision to find the STWARDNAME
lid=as.vector(row.names(bor#data))
pu=bor#data[row.names(bor#data)==lid,'STWARDNAME']
, then added in two arguments while making the map layerId = lid,popup = pu,. The pop up showed when the user clicked on an area
bor=subset(shapeData,shapeData$LA_NAME %in% input$LANAME)
lid=as.vector(row.names(bor#data))
pu=bor#data[row.names(bor#data)==lid,'STWARDNAME']
leaflet() %>% addTiles() %>%
setView(lng = llong, lat=llat,zoom=13) %>%
addPolygons(data=bor,weight=2,col = 'black',fillOpacity = 0.2,fillColor = bor$col,
layerId = lid,popup = pu,
highlightOptions = highlightOptions(color='white',weight=1,
bringToFront = TRUE)) %>%
addMarkers(lng = llong,lat=llat,popup=input$LANAME)
How can a popup stay open when clicking on another?
The MWE below show a popup when I click on the markers. Good. But when I click on a second marker I don't want the first popup to disappear. It should only disapear when clicking the close [x]. No popups should be visible before clicking on the markers.
library(leaflet)
the.points <- data.frame(latitude=c(63.136353,63.132935,63.128051),
longitude=c(21.928023,21.962601,21.893444),
text=c("One point", "A second point", "The third point"))
p <- leaflet(the.points)
p <- addTiles(p)
p <- addMarkers(p, lng=~longitude, lat=~latitude, popup=~text)
p
I tried with addPopups too, but they are all visible by default. If that can be changed it would be good (not sure how).
Was struggling with the same thing, finally this worked for me:
leaflet() %>% addTiles() %>%
addMarkers(
lng = -118.456554, lat = 34.085,
popup = "One popup",
popupOptions = popupOptions(autoClose = FALSE, closeOnClick = FALSE)) %>%
addMarkers(
lng = -118.456554, lat = 34.065,
popup = "Another popup",
popupOptions = popupOptions(autoClose = FALSE, closeOnClick = FALSE))
)