5

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);
    }
});
Tonio Liebrand
  • 17,189
  • 4
  • 39
  • 59
fifthace
  • 506
  • 1
  • 10
  • 33
  • I'm not sure if this is helpful but you can check out https://github.com/bhaskarvk/leaflet.extras. Maybe Bhaskar can assist at least. – Eli Berkow Jan 14 '20 at 11:53

0 Answers0