Search code examples
rr-leaflet

How to show path and distance on map with leaflet?


I would like to show the distance between two locations using the leaflet package in a shiny app. I don't know how to do it. A line should connect two points on a map and display the distance on it. Please find the sample image, this describes my expectation:

Path with distance


Solution

  • Try the below:

    library(leaflet)
    library(osrm)
    
    route = osrmRoute(c(115.6813467,-32.0397559), c(150.3715249,-33.8469759), overview = 'full')
    # 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))
    
    leaflet() %>% addTiles() %>% 
      addMarkers(c(115.6813467,150.3715249), c(-32.0397559,-33.8469759)) %>% 
      addPolylines(route$lon,route$lat, 
                   popup = paste(round(route_summary[1]/60), 'hr', br(), round(route_summary[2]), 'km'))
    

    I added route_simple in the code above but didn't use it. It just saves less points on the route so it's less detailed but runs quicker. Feel free to play around. I also used a popup instead of a label in my second example. You need to click on the route to open it.

    Label Example label example

    Popup Example popup example

    If you want a shiny app then see below:

    library(leaflet)
    library(osrm)
    
    route = osrmRoute(c(115.6813467,-32.0397559), c(150.3715249,-33.8469759), overview = 'full')
    # 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)
    
    library(shiny)
    
    ui <- fluidPage(
      leafletOutput('map')
    )
    
    server <- function(input, output, session) {
      output$map <- renderLeaflet({
        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))
      })
    }
    
    shinyApp(ui, server)