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

时间:2016-06-22 14:36:13

标签: r leaflet htmlwidgets rmaps

问题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)

问题3

事实上,我最初的问题是我无法在rmarkdown中编写代码,以便直接在html文档中生成地图。

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

1 个答案:

答案 0 :(得分:4)

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

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)