r-spatial / leafpop

Include Tables, Images and Graphs in Leaflet Popups
Other
113 stars 15 forks source link

compute graph to display via popupGraph by clicking on the marker #11

Closed OscarJanin closed 3 years ago

OscarJanin commented 5 years ago

I would like to open a popup with a unique plot for each of my marker in it on a map_marker_click using r leaflet and the leafpop library.

For each point when the user click on them the plot to display is computed.

Below is a reproductible code but it doesn't return any error.

Is it possible to run addPopupGraph() inside a map_marker_click event?

library(tidyverse)
library(ggplot2)
library(shiny)
library(leaflet)
library(leafpop)

id <- c(1,1,1,1,2,2,3,3,3,4)
lat <- c(49.823, 49.823, 49.823, 49.823, 58.478, 58.478, 57.478 , 57.478 , 57.478, 38.551)
lng <- c(-10.854, -10.854, -10.854, -10.854, -11.655, -11.655, 2.021 , 2.021 , 2.021, 5.256)
type <- c("A","C","B","B","C","A","B","A","C","B")
date <- c(152.5,307.5,145,481,152,109.5,258.5,107.5,186.5,150)
start <- c(123,235,135,192,149,101,205,75,155,100)
stop <- c(182,380,155,289,155,218,312,140,218,200)
myData <- data.frame(id,type,date,start,stop,lat,lng)

chronogramme<- function(dataId){

  dataFiltered<-filter(myData,id==dataId)

  p<- ggplot(dataFiltered,aes(type,date))+
    geom_linerange(aes(ymin=start,ymax=stop),size=5)+
    coord_flip()
  return(p)
}

ui <- fluidPage(
  leafletOutput("map"),
  plotOutput("plot")
)

server <- function(input, output, session) {

  #Sortie map
  output$map <- renderLeaflet({
    leaflet()%>%
      addProviderTiles(providers$CartoDB.Positron) %>% 
      addCircleMarkers(
        layerId=~id,
        data = myData,
        lat = myData$lat,
        lng = myData$lng,
        radius = 5,
        color = 'blue',
        stroke = FALSE,
        fillOpacity = 1,
        group = 'markers'
      )
  })

  observeEvent(input$map_marker_click,{
    p <- chronogramme(input$map_marker_click$id)
    isolate({
      leafletProxy("map") %>% addPopupGraphs(list(p), group = 'markers')
    })
  })

}

# Create Shiny app ----
shinyApp(ui = ui, server = server)
tim-salabim commented 4 years ago

Hi, I fear that in won't work this way. The problem is that when addPopupGraphs is called, it adds a dependency to the map. AFAIK htmlwidgets will not re-add an already existing dependency,

I think you'd need to re-think the app logic somehow. Can you not pre-create the plots and add all of them once?

tim-salabim commented 3 years ago

Closing here, please feel free to re-open if this is still an issue that needs attention here