2

I can't get crosstalk to work with leaflet and Polylines - here is an MWE:

library(crosstalk)
library(leaflet)

theta <- seq(0, 2*pi, len = 100)
dat <- data.frame(
  lon = cos(theta),
  lat = sin(theta),
  t = 1:100
)

sd <- SharedData$new(dat)

map <- leaflet() %>%
  addTiles() %>%
  addCircleMarkers(data = sd, lat = ~lat, lng = ~lon, color = "blue") %>%
  addPolylines(data = sd, lat = ~lat, lng = ~lon, color = "blue")

bscols(
  filter_slider("t", "Time", sd, column = ~t),
  map
)

The time filter_slider applies to the circle markers but not the polylines.

Happy to having a go at fixing this in the R leaflet package if someone can point me in the right direction. I.e. what would be required to change / implement? I assume the support is missing on the javascript side as of now?

2 Answers 2

6

UPDATE: Good News! @dmurdoch has submitted a pull request to add support for polylines and polygons. Using his version of crosstalk, you can now filter leaflet lines/polygons if they're sp objects (note, it doesn't seem to work with sf yet).

First you will need to install this version of crosstalk: devtools::install_github("dmurdoch/leaflet@crosstalk4")

Then you will need to make sure your features are Spatial objects, easy using rgdal or raster: shapes_to_filter <- raster::shapefile("data/features.shp") # raster import to 'Spatial Object' shapes_to_filter <- rgdal::readOGR("data/features.shp") # rgdal import to 'Spatial Object'

Or, if you use sf and dplyr for most spatial tasks (like me) convert an sf object to Spatial:

library(dplyr) library(sf) shapes_to_filter <- st_read("data/features.shp") %>% as('Spatial') # sf import to 'Spatial Object'

Then create an sd object for leaflet, and a data frame copy for the filters (IMPORTANT: note how the group for sd_df is set using the group names from the sd_map) :

library(crosstalk) sd_map <- SharedData$new(shapes_to_filter) sd_df <- SharedData$new(as.data.frame(shapes_to_filter@data), group = sd_map $groupName())

Create crosstalk filters using sd_df:

filter_select("filterid", "Select Filter Label", sd_df, ~SomeColumn)

Create the map using the sd_map object:

library(leaflet) leaflet() %>% addProviderTiles("OpenStreetMap") %>% addPolygons(data = sd_map)

And any linked tables/charts need to also use the sd_df object:

library(DT) datatable(sd_df)


Here's all of the sources for the solution:

GitHub Issue

Github pull request from dmurdoch to add support for polygons/lines

Original solution - with outdated method "sd$transform"

Updated example - with the new "group" method, but I couldnt get their RMD to work

0

As previously mentioned by Bhaskar Karambelkar: "crosstalk for now works only with markers and not polylines/polygons"

I hope this changes soon.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.