I am trying to use the SelectAreaFeature Leaflet JS plugin with Leaflet for R.
I have had success using other Leaflet JS plugins, but not the SelectAreaFeature plugin. Here is an MRE (requires the SelectAreaFeature js file):
library(leaflet)
library(htmltools)
library(shiny)
selectarea <- htmlDependency("SelectAreaFeature", "1",
src = c(file = paste0(getwd(),"/src")), # update path
script = "Leaflet.SelectAreaFeature.js")
registerPlugin <- function(map, plugin) {
map$dependencies <- c(map$dependencies, list(plugin))
map
}
server = function(input, output, session) {
output$map <- renderLeaflet({
leaflet() %>%
addProviderTiles(providers$CartoDB.Positron) %>%
setView(lng=9.4, lat=56.3, zoom = 8) %>%
registerPlugin(selectarea)
})
}
ui <- fluidPage(
tags$script(HTML(
'$("#enable-button").click(function(){
selectfeature = map.selectAreaFeature.enable();
selectfeature.options.color = "#663399" ;
selectfeature.options.weight = 3 ;
});'
)),
leafletOutput("map",height=700),
p(),
actionButton(inputId = 'enable-button',icon = icon("draw-polygon"),
label = 'Select area')
)
shinyApp(ui, server)
Using Chrome DevTools shows that the plugin is not a loaded source. I suspect an issue might be the way this plugin is written. The SelectAreaFeature.js has this key line:
L.Map.addInitHook('addHandler', 'selectAreaFeature', L.SelectAreaFeature);
Another Leaflet JS plugin, zoomdisplay, that I have successfully used in Leaflet for R has a different structure to its following addInitHook line:
L.Map.addInitHook(function () {
if (this.options.zoomDisplayControl) {
this.zoomDisplayControl = new L.Control.ZoomDisplay();
this.addControl(this.zoomDisplayControl);
}
});