Question 1 I try to save a leaflet map created with rMaps here, into a html file.
L2 <- Leaflet$new()
L2$setView(c(29.7632836, -95.3632715), 10)
L2$tileLayer(provider = "MapQuestOpen.OSM")
L2
library(htmlwidgets)
saveWidget(L2,"t.html")
But I got an error:
Error in envRefInferField(x, what, getClass(class(x)), selfEnv) :
‘width’ is not a valid field or method name for reference class “Leaflet”
Answer 1 Thanks to LukeA, we can use this syntaxe:
leaflet(width = "100%") %>%
addProviderTiles("MapQuestOpen.OSM") %>%
setView(-95.3632715, 29.7632836, zoom = 10) -> L2
Question 2 But then, how to add addAssets and 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
Answer 2 Again, thanks to LukeA, we have the answer:
L2$save(tf <- tempfile(fileext = ".html"),standalone=TRUE)
Question 3
In fact, my initial problem is that I can't write the code in rmarkdown, in order to generate directly the map in the html document.
Now I can save the map alone. But how to integrate it into the html document ? The rapide solution is to make an iframe. It there any other more elegant solutions ?
Although not a direct answer to your question, I suggest an alternative approach that yields a similar result:
library(leaflet)
library(htmlwidgets)
leaflet() %>%
addProviderTiles("MapQuestOpen.OSM") %>%
setView(-95.3632715, 29.7632836, zoom = 10) -> m
saveWidget(m, tf <- tempfile(fileext = ".html"))
or, using 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)