rr-leafletjupyter-irkernel

How to display interactive leaflet map in R notebook in colab


I am unable to plot an interactive map in colab

A workaround (static image) is in the second cell.

I expect an answer in r-leaflet.

Related blog


Solution

  • I came with this answer/workaround - third cell in colab

    if (system.file(package = "leaflet") == '') {
      install.packages("leaflet")
    }
    if (system.file(package = "htmlwidgets") == '') {
      install.packages("htmlwidgets")
    }
    if (system.file(package = "IRdisplay") == '') {
      install.packages("IRdisplay")
    }
    
    library(leaflet)
    library(htmlwidgets)
    library(IRdisplay)
    
    m = leaflet() %>% 
    #addTiles() 
    addTiles(urlTemplate = "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png") # colab compatibility
    
    saveWidget(m, 'demo1.html', selfcontained = TRUE)
    
    IaminColab<-TRUE
    
    if(IaminColab){  # does not work in jupyter
      demo<-readLines("demo1.html")
      demo<-gsub("%","%25",demo)
      demo<-gsub("#","%23",demo)
      demo<-gsub("\"","%22",demo)
      demo<-gsub("'" ,"%27",demo)
      demo<-gsub("\\n" ,"",demo)
      demo<-paste(demo, collapse="")
      display_html(paste0('<iframe src=',"\"data:text/html;charset=UTF-8,",demo," \" height=\"300\" width=\"500\"></iframe>") )
    } else { # does not work in colab
      display_html('<iframe src="demo1.html" width="500" height ="300"></iframe>')
    }
    

    enter image description here

    Sources: Package leaflet - map doesn't show
    Convert HTML to data:text/html link using JavaScript