1

问题 1 我尝试将使用 rMaps 创建的传单地图保存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 文档中呢?Rapide 的解决方案是制作一个 iframe。还有其他更优雅的解决方案吗?

4

1 回答 1

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)
于 2016-06-22T14:45:33.057 回答