I'm using an instance of OSRM (OpenStreetMap Routing Machine) to evaluate distance and time from different points. Using the API, I can retrieve information that I want and need especially the real route as a polyline.
Until today, I have plotted straight lines between start and end point.
segments(
lon_patient,lat_patient,lon_lieu,lat_lieu,col = transp_time,lwd = 3
)
Now I want to plot the polylines. But it is encoded (https://github.com/Project-OSRM/osrm-backend/wiki/Server-api#response-2). How can I draw it?
Thanks!
One (quick) way to get this going is to download the polyline.js file from the mapbox github repo then use the V8 package to do the hard work for you:
It returns a matrix of lat/lon pairs you should be able to work with.
A pure R/Rcpp answer would be better in the long run, though.
UPDATE
There is one! This came from: https://gist.github.com/diegovalle/916889 (I added the
require
s and combined some wordy0
assignments):That gets you a data frame vs a matrix. And is pure R. Not sure which one will be faster (if speed is a need).
UPDATE #2
There's another pure R implementation here: http://s4rdd.blogspot.com/2012/12/google-maps-api-decoding-polylines-for.html and it's much faster than the one above (see below for benchmarks).
Here's an Rcpp/C++11 version courtesy of https://mapzen.com/documentation/mobility/decoding/ :
Save that to
polyline.cpp
and just:Then you can:
Benchmarks
I sourced the two R function into the global environment and did the js & C++ equivalents for the javascript and C++ implementations.
The max value is pretty "out there" for
DecodeLineR
no matter what microbenchmark parameters I use. ThedecodeLine()
pure R version seems performant enough to not warrant incurring theV8
orRcpp
/C++11 dependency, but YMMV.FINAL UPDATE (MOAR BENCHMARKS)
I incorporated the
googleway::decode_pl()
function into the new benchmarks and used a much longer polyline. Benchmark code is below and the new plot is below that.