简体   繁体   中英

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

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>')
}

在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM