Search code examples
rr-leaflet

Dropdown filter in Leaflet for R


I have a leaflet map which I created in R and I would like to add a dropdown filter based on fields in a column. The code looks straightforward in JS, see example here Leaflet dropdown filter, however I can't figure out how to adjust the code for R.

library(leaflet.extras)

n = c(2, 3, 5) 
long = c(102.1,102.13,102.2) 
lat = c(55,55.1,55.15)
select_cols= c("a","b","c")
 df = data.frame(n, long, lat,select_cols)  


 pal <- colorFactor(c("navy", "red","green"), domain = c("a","b","c"))


 leaflet(df)%>% addTiles()%>%
   addCircleMarkers(lng = long,lat=lat,radius= ~n*2,
color=~pal(select_cols),stroke=F,fillOpacity = 1)

Here is the JS code that adds a dropdown filter.

var legend = L.control({position: 'topright'});
legend.onAdd = function (map) {
var div = L.DomUtil.create('div', 'info legend');
div.innerHTML = '<select><option>1</option><option>2</option>        
<option>3</option></select>';
div.firstChild.onmousedown = div.firstChild.ondblclick =         
L.DomEvent.stopPropagation;
return div;
};
legend.addTo(map);

I know how to add the "show hide layers" feature, however I have over 20 different fields and I think it would be easier if the user could select the associated field using a drop down box.


Solution

  • In case anyone is looking for something similar, I found a solution using crosstalk. See the code below for an example.

    library(crosstalk)
    library(tidyverse)
    library(leaflet.extras)
    
    quakes <- quakes %>%
      dplyr::mutate(mag.level = cut(mag,c(3,4,5,6),
      labels = c('3.01-4.00', '4.01-5.00', '5.01-6.00')))
    
    quakes_sd<- SharedData$new(quakes)
    
    map<- leaflet(quakes_sd)%>%addProviderTiles(providers$Esri.WorldTopoMap)%>%  addCircles()
    
    #add filter
    bscols(
    filter_select("Magnitude Level", "Magnitude Level", quakes_sd, ~mag.level)
      )
    
    bscols(map)