How to show path on map with leaflet?

I found this solution and try it, How to show path and distance on map with leaflet, shiny apps?

but when I run the code

library(leaflet)
library(osrm)


route = osrmRoute(c(115.6813467,-32.0397559), c(150.3715249,-33.8469759),overview = "simplified")
# route_simple = osrmRoute(c(115.6813467,-32.0397559), c(150.3715249,-33.8469759), overview = 'simplified')
route_summary = osrmRoute(c(115.6813467,-32.0397559), c(150.3715249,-33.8469759), overview = FALSE)

leaflet() %>% addTiles() %>% 
  addMarkers(c(115.6813467,150.3715249), c(-32.0397559,-33.8469759))%>% 
  addPolylines(route$lon,route$lat, 
               label = paste(round(route_summary[1]/60), 'hr - ', round(route_summary[2]), 'km'), 
               labelOptions = labelOptions(noHide = TRUE))

there is not any route$lon and route$lat found and it gives me this error

Error in validateCoords(lng, lat, funcName, mode = "polygon") : addPolylines requires non-NULL longitude/latitude values

Could you please help me?

Try to show route on map using leaflet

Upvotes: 0

Views: 93

Answers (1)

margusl
margusl

Reputation: 17314

In current version of osrm, osrmRoute() returns an sf object which can be passed to leaflet() :

library(leaflet)
library(osrm)

# osrmRoute() returns an sf object with a LINESTRING,
# also duration and distance atributes ...
route = osrmRoute(c(115.6813467,-32.0397559), c(150.3715249,-33.8469759), overview = "simplified")
route
#> Simple feature collection with 1 feature and 4 fields
#> Geometry type: LINESTRING
#> Dimension:     XY
#> Bounding box:  xmin: 115.7247 ymin: -34.73311 xmax: 150.3296 ymax: -31.35811
#> Geodetic CRS:  WGS 84
#>         src dst duration distance                       geometry
#> src_dst src dst 3029.825 3826.558 LINESTRING (115.7247 -32.05...

# ... which can be directly passed to leaflet() or layer functions as a data parameter;
# and releveant duration & distance values can be accessed through formula notation: 
# label = ~ sprintf("%d hr - %d km", round(duration/60), round(distance))
leaflet(route) |> 
  addTiles() |>
  addMarkers(c(115.6813467,150.3715249), c(-32.0397559,-33.8469759)) |>
  addPolylines(label = ~ sprintf("%d hr - %d km", round(duration/60), round(distance)),
               labelOptions = labelOptions(noHide = TRUE))

Created on 2024-03-12 with reprex v2.1.0

Upvotes: 0

Related Questions