Generate routes between two points in google maps on shiny

The code below generates maps with the leaflet library. Notice that I generate two maps, the first one shows all the clusters, in this case we have two. And the map further down shows a specific cluster that a given user wants to see. If you place the cursor on the points on the first map, you can see which are the properties of cluster 1 and which are the properties of cluster 2 (see Figure 1). In this case, properties 1 and 4 are from cluster 1 and 2 and 3 for the cluster 2. The code is working fine so far. What I would like to do:

  • I would like to route between the properties of the selected cluster, so as I have the lat and long of property 1 and lat and long of property 4 of cluster 1, for example, I would like to do the route through google maps (see Figure 2). So instead of putting this map 2 with leaflet of just showing the cluster properties, I would like you to do the route in google maps. Is there any way to do this?

Code executable below:

library(shiny)
library(rdist)
library(geosphere)
library(shinythemes)
library(leaflet)

function.cl<-function(df,k,Filter1){
  
  #database df
  df<-structure(list(Properties = c(1,2,3,4), 
                     Latitude = c(-23.8, -23.8, -23.9, -23.9), 
                     Longitude = c(-49.6, -49.3, -49.4, -49.6), 
                     Waste = c(526, 350, 526, 469)), class = "data.frame", row.names = c(NA, -4L))
  
 
  #clusters
  coordinates<-df[c("Latitude","Longitude")]
  d<-as.dist(distm(coordinates[,2:1]))
  fit.average<-hclust(d,method="average") 
  clusters<-cutree(fit.average, k) 
  nclusters<-matrix(table(clusters))  
  df$cluster <- clusters 
  
  #specific cluster and specific propertie
  df1<-df[c("Latitude","Longitude")]
  df1$cluster<-as.factor(clusters)
  df_spec_clust <- df[df$cluster == Filter1,]

  
  #Table to join df and df1
  data_table <- Reduce(merge, list(df, df1))
  
  #Color and Icon for map
  ai_colors <-c("red","gray","blue")
  
  clust_colors <- ai_colors[df$cluster]
  icons <- awesomeIcons(
    icon = 'ios-close',
    iconColor = 'black',
    library = 'ion',
    markerColor =  clust_colors)

    # Map for all clusters:
  m1<-leaflet(df1) %>% addTiles() %>%
    addAwesomeMarkers(lat=~Latitude, lng = ~Longitude, icon=icons, label=~as.character(df$Properties)) %>% 
    addLegend( position = "topright", title="Cluster", colors = ai_colors[1:max(df$cluster)],labels = unique(df$cluster))
  
  plot1<-m1
  
  # Map for specific cluster and propertie
  if(nrow(df_spec_clust)>0){
    clust_colors <- ai_colors[df_spec_clust$cluster]
    icons <- awesomeIcons(
      icon = 'ios-close',
      iconColor = 'black',
      library = 'ion',
      markerColor =  clust_colors)
    
    m2<-leaflet(df_spec_clust) %>% addTiles() %>%
      addAwesomeMarkers(lat=~Latitude, lng = ~Longitude, icon=icons, label=~cluster) 
    plot2<-m2} else plot2 <- NULL
  
  
  return(list(
    "Plot1" = plot1,
    "Plot2" = plot2,
    "Data" = data_table
  ))
}

ui <- bootstrapPage(
  navbarPage(theme = shinytheme("flatly"), collapsible = TRUE,
             "Cl", 
             tabPanel("",
                      sidebarLayout(
                        sidebarPanel(
                          tags$b(h3("Choose the cluster number?")),
                          sliderInput("Slider", h5(""),
                                      min = 2, max = 2, value = 2),
                        ),
                        mainPanel(
                          tabsetPanel(      
                            tabPanel("Mapa of all clusters", (leafletOutput("Leaf1",width = "95%", height = "600")))))
                        
                      ))),
  tabPanel("",
           sidebarLayout(
             sidebarPanel(
               selectInput("Filter1", label = h4("Select just one cluster to show"),""),
               
             ),
             mainPanel(
               tabsetPanel(
                 tabPanel("Map of specific cluster", (leafletOutput("Leaf2",width = "95%", height = "600")))))
           )))

server <- function(input, output, session) {
  
  Modelcl<-reactive({
    function.cl(df,input$Slider,input$Filter1)
  })
  
  output$Leaf1 <- renderLeaflet({
    Modelcl()[[1]]
  })
  
  output$Leaf2 <- renderLeaflet({
    Modelcl()[[2]]
  })
  
  observeEvent(input$Slider, {
    abc <- req(Modelcl()$Data)
    updateSelectInput(session,'Filter1',
                      choices=sort(unique(abc$cluster)))
  }) 

}

shinyApp(ui = ui, server = server)

Figure 1
enter image description here

Figure 2
enter image description here

Are you asking how to get started with querying the google api from R ?
If so, perhaps this would help
Introduction to package mapsapi (rstudio.com)

Thanks for reply @nirgrahamuk

I was working on this issue today and saw a resolution from the googleway package. I believe that I have solved the vast majority, the only thing that is not working is that for the generation of the second map I manually put the coordinates of the two properties ( df2<-google_directions(origin = df[1,2:3], destination = df[2,2:3], mode = "driving")), however, I would like that from the cluster selected in selectInput, the two properties were already recognized to generate the route. Do you happen to know how to adjust this? I'll insert the code and a figure below.

Note: Remember that the API key is required.

    library(shiny)
    library(rdist)
    library(geosphere)
    library(shinythemes)
    library(leaflet)
    library(googleway)
    
    
    set_key( "API KEY")
       
    function.cl<-function(df,k,Filter1){
      
      #database df
      df<-structure(list(Properties = c(1,2,3,4), 
                         Latitude = c(-24.930473, -24.924361,-24.95575,-24.95575), 
                         Longitude = c(-49.994889, -50.004343,-49.990162, -50.007371), 
                         Waste = c(526,350,525,523)), class = "data.frame", row.names = c(NA, -4L))
    
      
      #clusters
      coordinates<-df[c("Latitude","Longitude")]
      d<-as.dist(distm(coordinates[,2:1]))
      fit.average<-hclust(d,method="average") 
      clusters<-cutree(fit.average, k) 
      nclusters<-matrix(table(clusters))  
      df$cluster <- clusters 
      
      #specific cluster and specific propertie
      df1<-df[c("Latitude","Longitude")]
      df1$cluster<-as.factor(clusters)
      df_spec_clust <- df[df$cluster == Filter1,]
    
      
      #Table to join df and df1
      data_table <- Reduce(merge, list(df, df1))
      
      #Color and Icon for map
      ai_colors <-c("red","gray","blue")
      
      clust_colors <- ai_colors[df$cluster]
      icons <- awesomeIcons(
        icon = 'ios-close',
        iconColor = 'black',
        library = 'ion',
        markerColor =  clust_colors)
    
        # Map for all clusters:
      m1<-leaflet(df1) %>% addTiles() %>%
        addAwesomeMarkers(lat=~Latitude, lng = ~Longitude, icon=icons, label=~as.character(df$Properties)) %>% 
        addLegend( position = "topright", title="Cluster", colors = ai_colors[1:max(df$cluster)],labels = unique(df$cluster))
      
      plot1<-m1
      
      # Map for specific cluster and propertie
    
        df2<-google_directions(origin = df[1,2:3], destination = df[2,2:3], 
                               mode = "driving")
        
        df_routes <- data.frame(polyline = direction_polyline(df2))
        
        
        m2<-google_map(df_spec_clust) %>%
          add_polylines(data = df_routes, polyline = "polyline")
        
        plot2<-m2 
    
      return(list(
        "Plot1" = plot1,
        "Plot2" = plot2,
        "Data" = data_table
      ))
    }
    
    ui <- bootstrapPage(
      navbarPage(theme = shinytheme("flatly"), collapsible = TRUE,
                 "Cl", 
                 tabPanel("Map of all clusters",
                          sidebarLayout(
                            sidebarPanel(
                              tags$b(h3("Choose the cluster number?")),
                              sliderInput("Slider", h5(""),
                                          min = 2, max = 2, value = 2),
                            ),
                            mainPanel(
                              tabsetPanel(      
                                tabPanel("Solution", (leafletOutput("Leaf1",width = "95%", height = "600")))))
                            
                          ))),
      tabPanel("",
               sidebarLayout(
                 sidebarPanel(
                   selectInput("Filter1", label = h4("Select just one cluster to show"),""),
                   
                   h4("The distance is (km):"),
                   textOutput("dist"),
                   
                 ),
                 mainPanel(
                   tabsetPanel(
                     tabPanel("Map of specific cluster", ( google_mapOutput("G2",width = "95%", height = "600")))))
               )))
    
    server <- function(input, output, session) {
      
      Modelcl<-reactive({
        function.cl(df,input$Slider,input$Filter1)
      })
      
      output$Leaf1 <- renderLeaflet({
        Modelcl()[[1]]
      })
      
      output$G2 <- renderGoogle_map({
        Modelcl()[[2]]
      })
      
     # output$dist <- renderText({
       # Modelcl()[[3]]
     # })
    
      observeEvent(input$Slider, {
        abc <- req(Modelcl()$Data)
        updateSelectInput(session,'Filter1',
                          choices=sort(unique(abc$cluster)))
      }) 
    
    }
    
    shinyApp(ui = ui, server = server)

enter image description here

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.