0

Could you help me adjust the addPolylines on the second map ?? In the first it worked correctly, however in the second it did not show the red lines connecting one point to the other. I couldn't see what the error might be. I appreciate any help. I inserted an image below to illustrate.

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

function.cl<-function(df,k,Filter1,Filter2){
  
  #database df
  df<-structure(list(Properties = c(1,2,3,4,5,6,7), 
                     Latitude = c(-23.8, -23.8, -23.9, -23.9, -23.9,-23.4,-23.5), 
                     Longitude = c(-49.6, -49.3, -49.4, -49.8, -49.6,-49.4,-49.2), 
                     Waste = c(526, 350, 526, 469, 285, 433, 456)), class = "data.frame", row.names = c(NA, -7L))
  
  
  #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 <- df1[df1$cluster == Filter1,]
  df_spec_prop<-df[df$Properties==Filter2,]
  
  #Table to join df and df1
  data_table <- Reduce(merge, list(df, df1))
  
  #Color and Icon for map
  ai_colors <-c("red","gray","blue","orange","green","beige","darkgreen","lightgreen", "lightred", "darkblue","lightblue",
                "purple","darkpurple","pink", "cadetblue","white","darkred", "lightgray","black")
  clust_colors <- ai_colors[df$cluster]
  icons <- awesomeIcons(
    icon = 'ios-close',
    iconColor = 'black',
    library = 'ion',
    markerColor =  clust_colors)
  
  leafIcons <- icons(
    iconUrl = ifelse(df1$Properties,
                     "https://image.flaticon.com/icons/svg/542/542461.svg"
    ),
    iconWidth = 45, iconHeight = 40,
    iconAnchorX = 25, iconAnchorY = 12)
  html_legend <- "<img src='https://image.flaticon.com/icons/svg/542/542461.svg'>"
  
  # Map for all clusters:
  m1<-leaflet(df1) %>% addTiles() %>%
    addMarkers(~Longitude, ~Latitude, icon = leafIcons) %>%
    addAwesomeMarkers(lat=~df$Latitude, lng = ~df$Longitude, icon=icons, label=~as.character(df$cluster)) %>% 
    addPolylines(lat=~df$Latitude, lng = ~df$Longitude,color="red") %>% 
    addLegend( position = "topright", title="Cluster", colors = ai_colors[1:max(df$cluster)],labels = unique(df$cluster))
    
  plot1<-m1
  
  # Map for specific cluster and propertie
  m2<-leaflet(df_spec_clust) %>% addTiles() %>%
    addMarkers(~Longitude, ~Latitude, icon = leafIcons) %>%
    addAwesomeMarkers(lat=~df_spec_prop$Latitude, lng = ~df_spec_prop$Longitude, icon=icons, label=~as.character(df$cluster))%>% 
    addPolylines(lat=~df_spec_prop$Latitude, lng = ~df_spec_prop$Longitude,color="red")
    plot2<-m2
  
  
  return(list(
    "Plot1" = plot1,
    "Plot2" = plot2,
    "Data" = data_table
  ))
}

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

server <- function(input, output, session) {
  
  Modelcl<-reactive({
    function.cl(df,input$Slider,input$Filter1,input$Filter2)
  })
  
  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)))
  }) 
  
  observeEvent(input$Filter1,{
    abc <- req(Modelcl()$Data) %>% filter(cluster == as.numeric(input$Filter1))
    updateSelectInput(session,'Filter2',
                      choices=sort(unique(abc$Properties)))
  }) 
  
  
}

shinyApp(ui = ui, server = server)

enter image description here

Image as an example (Markers connect only with AwesomeMarkers)

enter image description here

Thank you very much friends!

Conflict with color of map 2

# 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
  

   for(i in 1:nrow(df_spec_clust)){
     df_line <- rbind(df_spec_prop[,c("Latitude","Longitude")],
                       df_spec_clust[i,c("Latitude","Longitude")])
      m2 <- m2 %>%
        addPolylines(data = df_line, 
                     lat=~Latitude, 
                     lng = ~Longitude,
                     color="red")
    }
    plot2<-m2

Warning: Error in eval: object 'm2' not found**

Community
  • 1
  • 1

1 Answers1

1

After building your map, you need to iterate over each pair of points to join with a line, for example with a for loop:

for(i in 1:nrow(df_spec_clust)){
    df_line <- rbind(df_spec_prop[,c("Latitude","Longitude")],
                     df_spec_clust[i,c("Latitude","Longitude")])
    m2 <- m2 %>%
      addPolylines(data = df_line, 
                   lat=~Latitude, 
                   lng = ~Longitude,
                   color="red")
}
HubertL
  • 19,246
  • 3
  • 32
  • 51
  • Thanks for the reply friend, but in my example the m2 is considering df_spec_clust and df_spec_prop. In what you adjusted it only considered just df_spec_clust. I need to insert the df_spec_prop too. In the image above, note that on map 2, the icons are different, just because there is df_spec_clust and df_spec_prop. Thanks again –  May 13 '20 at 01:46
  • Sorry I don't understand what you're trying to achieve. What should be marked with markers, and what should be linked by line? – HubertL May 13 '20 at 03:25
  • Hi friend, I will try to express myself better. Markers is df_spec_clust (database df1). However, there is also df_spec_prop (database df), so in my code I did addAwesomeMarkers too, because it's another database. Therefore, I would like to insert an addPolylines to link to each other on the map. In the code I made it showed both, but I was unable to insert addPolylines. Thanks again. –  May 13 '20 at 04:21
  • So you want simple markers on df_spec_clust and awsome markers on df_spec_prop? To draw a line between points in one dataset to points to another, on need to make a third dataset. With which point in the frst dataset do you join a point of the second dataset? Please update your question with a drawing (paint/gimp) of what you want. – HubertL May 13 '20 at 19:00
  • Thanks for the answer HubertL. Yes, in fact I would like the points made by Markers (df_spec_clust - database df1) to be connected only with addAwesomeMarkers (df_spec_prop - database df). I inserted an image above to illustrate, notice that it has 1 awsome markers and it is connected to the two Markers. Sorry for the inconvenience, if you can do something like that in the code, I try to adjust it to my case. –  May 13 '20 at 20:42
  • Is it too difficult to make friends? Giving me some tips would help me a lot. –  May 14 '20 at 22:20
  • Very good, I would never think that way. I will accept your answer. One problem I had is that it caused conflict in relation to the colors of map 2. In another question you helped me to solve this, but when I inserted this code of yours with the ```if (nrow (df_spec_clust)> 0``` which refers to the colors of the second map, it gives an error ```Warning: Error in eval: object 'm2' not found```. I will insert above the code I used to generate map 2. However, if you find it necessary for a new question, I will do it. Thanks again! –  May 15 '20 at 23:23
  • sorry, please ask a new question. – HubertL May 16 '20 at 00:56
  • New question: https://stackoverflow.com/questions/61830727/conflict-when-generating-addpolynes-on-the-map-made-by-leaflet Thank you very much! –  May 16 '20 at 01:23
  • There was an answer in the question above, but I think he did not understand correctly. I believe that you are the most ideal person to answer, since it helped me both in generating the colors of map 2 and adding the function of addPolyines. –  May 16 '20 at 15:52
  • Hi HubertL, I would like to know if you could give me a hand in relation to the issue mentioned above (https://stackoverflow.com/questions/61830727/conflict-when-generating-addpolylines-on-the-map-made-by-leaflet). I tried, but I couldn't solve it. Thank you very much! –  May 19 '20 at 19:05
  • I did. I think you'd learn a lot about shiny by reading my other answers [here](https://stackoverflow.com/search?tab=votes&q=user%3a5038107%20%5bshiny%5d) – HubertL May 19 '20 at 21:02