Clicking a leaflet marker takes you to URL

早过忘川 提交于 2019-12-05 11:04:09

You could use htmltools or htmlwidgets to add an onclick event with javascript:

Solution 1) with htmltools:

library(leaflet)
map <- leaflet() %>% 
  addTiles() %>%
  addMarkers(-122.327298, 47.597131, popup =  'LINK',
             options = popupOptions(closeButton = FALSE)
  )

library(htmltools)
browsable(
  tagList(
    list(
      tags$head(
        tags$script(
          '
         document.addEventListener("DOMContentLoaded", function(){
           var marker = document.getElementsByClassName("leaflet-pane leaflet-marker-pane");
           var openLink = function() {
             window.open("https://www.stackoverflow.com")
           };
           marker[0].addEventListener("click", openLink, false);
         })
          '
        )
      ),
      map
    )
  )
)

Solution 2 - with htmlwidgets:

library(leaflet)
library(htmlwidgets)
leaflet() %>% 
  addTiles() %>%
  addMarkers(-122.327298, 47.597131, popup =  'LINK',
             options = popupOptions(closeButton = FALSE)
  ) %>%
  onRender('
    function(el, x) {
      var marker = document.getElementsByClassName("leaflet-pane leaflet-marker-pane");
      var openLink = function() {
        window.open("https://www.stackoverflow.com")
      };
      marker[0].addEventListener("click", openLink, false);
    }
  ')

Different url for each marker:

This is a dirty approach and shows the general way. I lack time to get comfortable with closures in JS again to add a loop.

One could look here: addEventListener using for loop and passing values. And data can be passed from R to JS with the onRender function. Maybe i find time on the weekend again or you/someone adds this part. Feel free to leave the question open,..

 jsCode <- paste0('
 function(el, x) {
  var marker = document.getElementsByClassName("leaflet-marker-icon leaflet-zoom-animated leaflet-interactive");
  marker[0].onclick=function(){window.open("https://stackoverflow.com/questions/tagged/python");};
  marker[1].onclick=function(){window.open("https://stackoverflow.com/questions/tagged/r");};
}
 ')


 library(leaflet)
 library(htmlwidgets)
 leaflet() %>% 
   addTiles() %>%
   addMarkers(lng = df$lng, lat = df$lat, popup =  'LINK',
              options = popupOptions(closeButton = FALSE)
   ) %>%
   onRender(jsCode)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!