I saw the following issue posted to the rMaps github repo today.
I am new to using rMaps and leaflet. I would like to plot the route between two locations. The leaflet routing machine plugin allows us to do this (https://github.com/perliedman/leaflet-routing-machine). I am not quite sure how to use the functions
addAssets()
andsetTemplate()
to be able to use this plugin.
This was a good exercise for me to test whether these newly introduced mechanisms addAssets
and setTemplate
would allow one to easily extend the base leaflet binding in rMaps.
Let us start by creating the base map.
library(rMaps)
map = Leaflet$new()
map$setView(c(40.73846, -73.99413), 16)
map$tileLayer(provider = 'Stamen.TonerLite')
In order to display the map in the notebook, we need a small wrapper function.
display_chart = function(viz){
y = paste(capture.output(viz$show('iframesrc', cdn = TRUE)), collapse = "\n")
IRdisplay::display_html(y)
}
We are now ready to display the map in the notebook.
display_chart(map)
We now want to add a route between the following waypoints. I have chosen the data structure to be an unnamed list of vectors, since it converts easily to the JSON structure expected by by routing plugin.
mywaypoints = list(c(40.74119, -73.9925), c(40.73573, -73.99302))
In order to use the routing plugin, we first need to add the required js/css assets. I introduced the addAssets
method in the dev
version of rCharts
precisely to serve this need (NOTE: It is currently a little buggy in terms of order in which the assets are specified, but I will take care of that this week).
map$addAssets(
css = "http://www.liedman.net/leaflet-routing-machine/dist/leaflet-routing-machine.css",
jshead = "http://www.liedman.net/leaflet-routing-machine/dist/leaflet-routing-machine.min.js"
)
routingTemplate = "
<script>
var mywaypoints = %s
L.Routing.control({
waypoints: [
L.latLng.apply(null, mywaypoints[0]),
L.latLng.apply(null, mywaypoints[1])
]
}).addTo(map);
</script>"
map$setTemplate(
afterScript = sprintf(routingTemplate, RJSONIO::toJSON(mywaypoints))
)
display_chart(map)