如何将传单地图(使用 rMaps 创建)保存为 html 小部件?

How to save a leaflet map (created with rMaps) as a html widget?

问题 1 我尝试将使用 rMaps here 创建的传单地图保存到 html 文件中。

L2 <- Leaflet$new()
L2$setView(c(29.7632836,  -95.3632715), 10)
L2$tileLayer(provider = "MapQuestOpen.OSM")
L2
library(htmlwidgets)

saveWidget(L2,"t.html")

但是我得到一个错误:

Error in envRefInferField(x, what, getClass(class(x)), selfEnv) : 
  ‘width’ is not a valid field or method name for reference class “Leaflet”

回答 1 感谢 LukeA,我们可以使用这个语法:

leaflet(width = "100%") %>% 
  addProviderTiles("MapQuestOpen.OSM") %>% 
  setView(-95.3632715, 29.7632836, zoom = 10) -> L2 

问题 2 但是,如何添加 addAssets 和 setTemplate:

# Add leaflet-heat plugin. Thanks to Vladimir Agafonkin
L2$addAssets(jshead = c(
  "http://leaflet.github.io/Leaflet.heat/dist/leaflet-heat.js"
))

# Add javascript to modify underlying chart
L2$setTemplate(afterScript = sprintf("
<script>
  var addressPoints = %s
  var heat = L.heatLayer(addressPoints).addTo(map)           
</script>
", rjson::toJSON(crime_dat)
))

L2

回答 2 再次感谢 LukeA,我们得到了答案:

L2$save(tf <- tempfile(fileext = ".html"),standalone=TRUE)

问题三

其实我最初的问题是我不能在rmarkdown中写代码,为了直接在html文档中生成地图。

现在我可以单独保存地图了。但是如何将其集成到 html 文档中呢?快速解决方案是制作一个 iframe。还有其他更优雅的解决方案吗?

虽然不是您问题的直接答案,但我建议采用另一种方法来产生类似的结果:

library(leaflet)
library(htmlwidgets)
leaflet() %>% 
  addProviderTiles("MapQuestOpen.OSM") %>% 
  setView(-95.3632715, 29.7632836, zoom = 10) -> m 
saveWidget(m, tf <- tempfile(fileext = ".html"))

或者,使用 rMaps:

library(plyr)
library(rCharts)
library(rMaps)
data(crime, package = 'ggmap')
crime_dat = ddply(crime, .(lat, lon), summarise, count = length(address))
crime_dat = toJSONArray(na.omit(unname(crime_dat)), json = F)

L2 <- Leaflet$new()
L2$setView(c(29.7632836,  -95.3632715), 10)
L2$tileLayer(provider = "MapQuestOpen.OSM")
# Add leaflet-heat plugin. Thanks to Vladimir Agafonkin
L2$addAssets(jshead = c(
  "http://leaflet.github.io/Leaflet.heat/dist/leaflet-heat.js"
))
# Add javascript to modify underlying chart
L2$setTemplate(afterScript = sprintf("
<script>
  var addressPoints = %s
  var heat = L.heatLayer(addressPoints).addTo(map)           
</script>
", rjson::toJSON(crime_dat)
))

L2$save(tf <- tempfile(fileext = ".html"),standalone=TRUE)