trafficonese / leaflet.extras

Extra functionality for leaflet R package.
https://trafficonese.github.io/leaflet.extras/
GNU General Public License v3.0
211 stars 74 forks source link

How to transition from Heatmap to circle markers on zooming? #193

Closed chintanp closed 2 months ago

chintanp commented 4 years ago

I am wondering if it would be possible to recreate the mapbox-like heatmap in R+Leaflet(.x). The idea is that the upon zooming the heatmap layer transitions to circle markers.

trafficonese commented 2 months ago

Unfortunately, the example link doesnt exist anymore.

Anyway, so far there is no automatic way of doing this. But you can certainly do it manually and show the heatmap with map-zoom levels < 7 and the circle markers with zoom levels > 7.

Here is an example in Shiny:

library(shiny)  
library(leaflet)

ui <- fluidPage(
  verbatimTextOutput("zoomlevel"),
  leafletOutput("map", height = 800)
)

server <- function(input, output, session) {
  output$map <- renderLeaflet({
    leaflet()  %>% 
      addTiles() %>% 
      setView(178, -20, 5)
  })

  output$zoomlevel <- renderPrint({
    paste0("Zoom level: ", req(input$map_zoom))
  })
  observe({
    zoom <- req(input$map_zoom)
    if (zoom < 7) {
      leafletProxy("map") %>%
        hideGroup("markers") %>% 
        showGroup("heatmap") %>% 
        addHeatmap(data = quakes,
            lng = ~long, lat = ~lat, intensity = ~mag,
            blur = 20, max = 0.05, radius = 15, 
            group = "heatmap")
    } else {
      pal <- colorNumeric("inferno", quakes$depth)
      leafletProxy("map") %>%
        hideGroup("heatmap") %>% 
        showGroup("markers") %>% 
        leaflet::addCircleMarkers(
          data = quakes, color = ~pal(depth),
          lng = ~long, lat = ~lat, radius = 4,
          group = "markers")
    }
  })
}
shinyApp(ui, server)