I'd like to build a map where when a state is clicked, it will open a hyperlink url in a new tab. I've been searching around for answers and can't quite get it to work for r leaflet. I believe I need to edit the json in the onRender
but it seems I'm not doing it right.
Thanks so much!!
library(tidyverse)
library(tigris)
library(leaflet)
state <-
states(
cb = TRUE
) %>%
filter(STUSPS %in% c('CA', 'WA', 'MD')) %>%
mutate(win_url =
case_when(
STUSPS == 'CA' ~ str_c('<a href=https://shiny.demog.berkeley.edu/alexramiller/kqed-evictions/>California Evictions</a>'),
STUSPS == 'WA' ~ str_c('<a href=https://evictions.study/washington/maps/summary.html>Washington Evictions</a>'),
STUSPS == 'MD' ~ str_c('<a href=https://evictions.study/maryland/report/baltimore.html>Maryland Evictions</a>')))
leaflet(state) %>%
addMapPane(name = "polygons", zIndex = 410) %>%
addMapPane(name = "maplabels", zIndex = 420) %>% # higher zIndex rendered on top
htmlwidgets::onRender('function onclick(e) {
window.open(e.target.feature.properties.win_url);
}') %>%
addProviderTiles("CartoDB.PositronNoLabels") %>%
addProviderTiles("CartoDB.PositronOnlyLabels",
options = leafletOptions(pane = "maplabels"),
group = "map labels") %>%
addPolygons(
# label = ~'<a href="https://shiny.demog.berkeley.edu/alexramiller/kqed-evictions/">California Evictions</a>', # this is an option but not preferred
fillOpacity = .5,
color = ~'Red',
stroke = TRUE,
weight = 1,
opacity = .5,
highlightOptions = highlightOptions(
color = "#ff4a4a",
weight = 5,
bringToFront = TRUE
)
)
CodePudding user response:
Using the answer from Clicking a leaflet marker takes you to URL and looping through, from addEventListener using for loop and passing values, seems to work:
jsCode <- paste0('
function(el, x, data) {
var marker = document.getElementsByClassName("leaflet-interactive");
for(var i=0; i < marker.length; i ){
(function(){
var v = data.win_url[i];
marker[i].addEventListener("click", function() { window.open(v);}, false);
}());
}
}
')
And run
leaflet(state) %>%
addMapPane(name = "polygons", zIndex = 410) %>%
addMapPane(name = "maplabels", zIndex = 420) %>%
addProviderTiles("CartoDB.PositronNoLabels") %>%
addProviderTiles("CartoDB.PositronOnlyLabels",
options = leafletOptions(pane = "maplabels"),
group = "map labels") %>%
addPolygons(
fillOpacity = .5,
color = 'Red',
stroke = TRUE,
weight = 1,
opacity = .5,
highlightOptions = highlightOptions(
color = "#ff4a4a",
weight = 5,
bringToFront = TRUE
)
) %>%
htmlwidgets::onRender(jsCode, data=state)
I had to rejig the state URLs
state <-
states(
cb = TRUE
) %>%
filter(STUSPS %in% c('CA', 'WA', 'MD')) %>%
mutate(win_url =
case_when(
STUSPS == 'CA' ~ 'https://shiny.demog.berkeley.edu/alexramiller/kqed-evictions/',
STUSPS == 'WA' ~ 'https://evictions.study/washington/maps/summary.html',
STUSPS == 'MD' ~ 'https://evictions.study/maryland/report/baltimore.html'))