router.Rdrouter initializes a GraphHopper router with a specific profile and data sources.
route computes a route using the specified router.
gh.profile defines a new routing profile
router(osm.file, path = "graphhopper-cache", profiles = "car", open = TRUE,
make.default = TRUE)
route(x, ...)
# S3 method for class 'matrix'
route(x, profile, times, alt=FALSE, output=c("matrix","sf","gh"),
silent=FALSE, threads=1L, router=.default(), ...)
# Default S3 method
route(x, start.lon, end.lat, end.lon, ...)
gh.profile(name, vehicle = name, weighting = "fastest", turn.costs = FALSE)
gh.translation(locale)string, path to the Open Street Map file used for routing
string, path to the GraphHopper cache. If it doesn't exist the cache will be created when first used
either a character vector or a list with one or more
objects returned from gh.profile(). This determines the
properties for the routing such as available means of transport, speeds,
turn penalties etc.
logical, if TRUE then the returned object can be
used for routing. If FALSE then the cache is created and
saved for later use, but no router is created for the current
session.
logical, if TRUE then the resulting
router is used as the default router for subseqeunt operations
object specifying the waypoints for the routes. See details for the supported input specifications.
scalar numeric, longitude of the starting point
scalar numeric, latitude of the end point
scalar numeric, longitude of the end point
either a string or a ghprofile object. If not
specified, defaults to the first profile of the router
desired output format: "matrix" for a matrix
describing the paths, "sf" for a data frame with a
"sfc" geometry column or "gh" GraphHoppe objects.
optional, vector of start times for time-dependent routing (such as public transport)
logical, if TRUE then warnings (such as
routing errors) are suppressed
logical, if TRUE then multiple alternative routes
are included in the result is available, otherwise only the best
route is reported in each case. Note that only the "gh"
format supports multiple routes per query.
integer, number of parallel threads to use for the routing.
For large matrices on private machines parallel::detectCores()
or similar may make sense
object returned from the router() function
string, name of the profile
string, mode of transport
string, weighting type
logical, whether to use turn costs
string, name of the language locale
parameters passed to methods
router must be called at least once to initialize the routing
parameters.
gh.profile defines a profile to be used in the router. Note
that a new cache must be built any time the profiles are changed.
route calculates one or more routes for each source/destination
pair. The matrix form requires a matrix with exactly 4 columns
specifying latitude and longitude of the start and end point
respectiely. Each row of the input matrix will have exactly one entry in
the result.
The scalar (default) version is just a wrapper for
matrix(c(start.lat, start.lon, end.lat, end.lon), 1).
Note that due to R method argument consistency requirements the first
argument of the default method is actually called x even though
it would better be named start.lat.
gh.translation loads translation from GraphHopper for
a given language locale and return the corresponding Java object.
"en" is always guaranteed to exist, others depend on the
GraphHopper installation.
router returns a router object.
route: the value depends on the "output" argument.
The "matrix" output is a matrix with columns "lat",
"lon" and "index" where "index" is the row number
in the input. Note that routing errors may occur (e.g. if the endpoint
is not near any roads) in which case the corresponding row may not
appear in the output. Use output="gh" for comprehensive error
reporting.
The "sf" output produces a data frame with a geometry column
representing the best path. It case of an error an empty line string is
used. Note that this output type requires the sf package.
The "gh" output produces an object of the class
GHRoutes
which holds the corresponding Java objects and thus allows for explicit
queries for different aspects of the routes including the support for
alternative routes.
gh.translation returns a Java object of the class
com.graphhopper.util.TranslationMap.
gh.profile returns a Java object of the class
com.graphhopper.config.Profile. Note that since it is a Java
object it can be modified by calling methods on it before passing
it to router.
The router() uses the rJava package to perform the
routing using the GraphHopper Java classes. GraphHopper may need
significant amount of RAM depending on the size of the map used. For
larger maps it is recommended to increase the amount of memory
available to Java by setting the java.parameters option
before the first call to router(), e.g.:
options(java.parameters="-Xmx8g")
will allow Java to use up to 8Gb of memory. Note that the amount of Java memory cannot be changed once Java is initialized, so if you load any other R package which uses Java it may have already limited the memory usage, so either setting the option early or starting the router first is a good option.
The functions above are a very thin API over GraphHopper Java
classes. It is possible to create more complex routing constraints by
using the Java classes directly. For example, the gh.profile
function returns an object of the class
com.graphhopper.config.Profile which can be further mutated
before passing it to the router. It corresponds directly to the
profiles: section of the YAML config files in the GraphHopper
documentation. By default all entries in profiles
are also automatically added to the contraction hierarchies
(see profiles_ch: section and
com.graphhopper.config.CHProfile).
dst <- tempfile("osm", fileext=".pbf")
cache <- tempfile("router-cache")
## download OSM map of Cyprus
download.file("https://download.geofabrik.de/europe/cyprus-latest.osm.pbf", dst, mode="wb")
library(ghroute)
## create router for Cyprus with defaults car and fastest
router(dst, cache)
#> [1] "Java-Object{nz.urbanek.RGH.GHRouter@2dc9b0f5}"
## compute single route between two points
rt = route(34.7592, 32.4123, 34.7996, 32.4517)
## by default the result is a lat/lon matrix
str(rt)
#> num [1:138, 1:2] 34.8 34.8 34.8 34.8 34.8 ...
#> - attr(*, "dimnames")=List of 2
#> ..$ : NULL
#> ..$ : chr [1:2] "lat" "lon"
par(mar=rep(0,4))
plot(rt[,2], rt[,1], ty='l', asp=1/cos(32.4/180*pi))
## it is also possible to compute multiple different
## routes by supplying a start-end matrix
m = matrix(c(34.7592, 32.4123, 34.7996, 32.4517,
34.7592, 32.4123, 34.6791, 33.044,
34.9827, 33.7348, 35.1716, 33.3616),,4,TRUE)
## the result is a big matrix with "index" column
## refering to the input row
rts = route(m)
str(rts)
#> num [1:1189, 1:3] 34.8 34.8 34.8 34.8 34.8 ...
#> - attr(*, "dimnames")=List of 2
#> ..$ : NULL
#> ..$ : chr [1:3] "lat" "lon" "index"
## it is possible to split the result into a list of
## matrices - each for one input row
res = rts2list(rts, nrow(m))
str(res)
#> List of 3
#> $ : num [1:138, 1:3] 34.8 34.8 34.8 34.8 34.8 ...
#> ..- attr(*, "dimnames")=List of 2
#> .. ..$ : NULL
#> .. ..$ : chr [1:3] "lat" "lon" "index"
#> $ : num [1:655, 1:3] 34.8 34.8 34.8 34.8 34.8 ...
#> ..- attr(*, "dimnames")=List of 2
#> .. ..$ : NULL
#> .. ..$ : chr [1:3] "lat" "lon" "index"
#> $ : num [1:396, 1:3] 35 35 35 35 35 ...
#> ..- attr(*, "dimnames")=List of 2
#> .. ..$ : NULL
#> .. ..$ : chr [1:3] "lat" "lon" "index"
plot(rts[,2], rts[,1], ty='n', asp=1/cos(32.4/180*pi))
for (o in res) lines(o[,2], o[,1])
## if you have sf package, you can get sfc instead:
have.sf <- requireNamespace("sf", quietly=TRUE)
if (have.sf) {
rts = route(m, output="sf")
print(rts)
plot(rts$geometry)
}
## the maximum flexilibity is with "gh" output
rts = route(m, output="gh")
rts
#> GHRoutes: 3 routing requests, 3 successful 0 failed.
#> GHPath of 138 points
#> GHPath of 655 points
#> GHPath of 396 points
rts[[1]]
#> GHPath of 138 points
#> lat lon
#> [1,] 34.75920 32.41225
#> [2,] 34.75950 32.41227
#> [3,] 34.76020 32.41225
#> [4,] 34.76046 32.41227
#> [...]
## expert use - return turn-by-turn instructions by querying the Java object
## get the instructions object
ins <- rts[[1]]$path$getInstructions()
## use English locale
tr <- gh.translation("en")
## get the descriptions
sapply(seq.int(ins$size()),
function(j) ins$get(j - 1L)$getTurnDescription(tr))
#> [1] "continue onto Apostolou Pavlou, B20"
#> [2] "At roundabout, take exit 2 onto Λεωφόρος Αποστόλου Παύλου, B20"
#> [3] "turn left onto Evagora Pallikaridi, B7"
#> [4] "At roundabout, take exit 3 onto E710"
#> [5] "turn slight left onto Eleftheriou Venizelou Avenue, E710"
#> [6] "keep left onto Vasileos Constantinou XIII, U68"
#> [7] "At roundabout, take exit 2 onto Anavargos Avenue"
#> [8] "At roundabout, take exit 2 onto Αριστοτέλους Σάββα"
#> [9] "turn right"
#> [10] "arrive at destination"
## clean up
unlink(c(dst, cache), TRUE, FALSE, FALSE)