r - Sync two leaftlet maps on different tabs in RMarkdown with Shiny -
running issues syncing 2 leaflet maps on different tabs.
after looking @ previous entries (synchronizing 2 leaflet maps in r / rmarkdown), solution provided @timsalabim not work because maps on different tabs.
here mwe rmarkdown example:
--- title: "questionforstackoverflow" output: flexdashboard::flex_dashboard: runtime: shiny --- ```{r setup, include=false} library(flexdashboard) library(shiny) library(leaflet) ``` tab 1 ====================================================================== ```{r tab1} output$map1 <- renderleaflet( leaflet() %>% addprovidertiles("cartodb.positron") %>% setview(-93.65, 42.0285, zoom = 4) ) leafletoutput("map1") ``` tab 2 ====================================================================== ```{r tab2} output$map2 <- renderleaflet( leaflet() %>% addprovidertiles("cartodb.positron") %>% setview(-93.65, 42.0285, zoom = 4) ) leafletoutput("map2") ``` i want 2 way change. view changes map1 -- changes map2 or changes map2 change map1.
ideally: if scroll st. louis on map1, map2 have same zoom level on st. louis.
right now, there no interactivity between 2 maps. there way make them sync?
you can use leafletproxy() : see here : https://rstudio.github.io/leaflet/shiny.html
for particular problem, here's idea :
--- title: "questionforstackoverflow" output: flexdashboard::flex_dashboard: runtime: shiny --- ```{r setup, include=false} library(flexdashboard) library(shiny) library(leaflet) ``` tab 1 ====================================================================== ```{r tab1} output$map1 <- renderleaflet( leaflet() %>% addprovidertiles("cartodb.positron") %>% setview(-93.65, 42.0285, zoom = 4) ) actionbutton("syncmap1", "fit map2 bounds") leafletoutput("map1") observeevent(input$syncmap1,{ map2coords <- input$map2_bounds map1proxy <- leafletproxy("map1") map1proxy %>% fitbounds(lng1 = map2coords$east, lat1 = map2coords$north, lng2 = map2coords$west, lat2 = map2coords$south) }) ``` tab 2 ====================================================================== ```{r tab2} output$map2 <- renderleaflet( leaflet() %>% addprovidertiles("cartodb.positron") %>% setview(-93.65, 42.0285, zoom = 4) ) actionbutton("syncmap2", "fit map1 bounds") leafletoutput("map2") observeevent(input$syncmap2,{ map1coords <- input$map1_bounds map2proxy <- leafletproxy("map2") map2proxy %>% fitbounds(lng1 = map1coords$east, lat1 = map1coords$north, lng2 = map1coords$west, lat2 = map1coords$south) }) ``` the idea retrieve coordinates of other map when clicking on buttons, , sync view then.
minor problem : view not synced : better find centroid of displayed map , use setview() using input$map1_zoom.
major problem : means using buttons, not user-friendly. theoritically, use observe() block reflect coordinates of each map other. tried , it's quite buggy, because of "infinite" loop there micro-variations in coordinates.
Comments
Post a Comment