r-spatial / leafem

leaflet extensions for mapview
https://r-spatial.github.io/leafem/
Other
108 stars 30 forks source link

added event listeners for click and mouseover events in addFgb() #64

Closed dfriend21 closed 1 year ago

dfriend21 commented 1 year ago

This adds the functionality mentioned in #63 (adding event listeners to polygons added via addFgb() so that you can respond to click and mouseover events in Shiny). I copy-and-pasted the mouseHandler function from the leaflet package (link) then used it to add event listeners for "click", "mouseover", and "mouseout" events in the functions addFlatGeoBuf() and addFlatGeoBufFiltered() (in fgb.js).

As a side note, I noticed when doing some testing that a recent commit (873ac24) seems to have broken addFgb() when minZoom is set - the polygons were not being added to the map when I provided a value for minZoom. The culprit appears to be the line updateResults = _.throttle(updateResults, 1000); in fgb.js, which had been commented out previously but was uncommented in that commit. When I re-commented that out, it worked.

Here's a small Shiny example to demonstrate.

example ```r library(leafem) library(leaflet) library(shiny) library(terra) # load in sample data shp_path <- system.file("ex/lux.shp", package="terra") shp <- vect(shp_path) shp_ext <- unname(as.vector(ext(shp))) # save out half of the features as a .fgb fgb_path1 <- tempfile(fileext = ".fgb") writeVector(shp[1:4,], fgb_path1, filetype = "FlatGeobuf") fgb_path2 <- tempfile(fileext = ".fgb") writeVector(shp[5:8,], fgb_path2, filetype = "FlatGeobuf") ui <- fluidPage( leafletOutput("map") ) server <- function(input, output){ output$map <- renderLeaflet({ leaflet("map") %>% fitBounds(shp_ext[1], shp_ext[3], shp_ext[2], shp_ext[4]) %>% addTiles(group = "Streets") %>% addFgb(fgb_path1, layerId = "addFgb1", fill = TRUE, fillColor = "blue", fillOpacity = 0.2) %>% addFgb(fgb_path2, # this one uses the 'minZoom' argument so that the 'addFlatGeoBufFiltered' JS function gets called layerId = "addFgb2", fill = TRUE, color = "darkgreen", fillColor = "darkgreen", fillOpacity = 0.2, minZoom = 5 , maxZoom = 52) %>% addPolygons(data = shp[9:12], color = "red") }) # show a notification when a shape is clicked observeEvent(input$map_shape_click, { event <- input$map_shape_click showNotification("click registered", type = "error", duration = NULL) }) } shinyApp(ui = ui, server = server) ```
tim-salabim commented 1 year ago

Thanks! I'll have a look next week. Off to a skit rip now

tim-salabim commented 1 year ago

Works like a charm thanks!

tim-salabim commented 1 year ago

@dfriend21 may I add you as a contributor to DESCRIPTION? If so, what's your email?

dfriend21 commented 1 year ago

Yep - for email you can use dafriend.r@gmail.com. Thanks for taking a look at this!