Using markerClusterOptions with SpatialPolygons in Leaflet - r

I am using the package Leaflet to plot around 25.000 polygons on a map. Because of this large number of polygons I want to make use of markerClusterOptions.
This is what I would like to do:
leaflet() %>%
addTiles() %>%
addPolygons(data=sp_polygons,
clusterOptions = markerClusterOptions())
But addPolygons doesn't know clusterOptions.
What is possible, is to do the following
leaflet() %>%
addTiles() %>%
addMarkers(data=coordinates(sp_polygons),
clusterOptions = markerClusterOptions())
But when I zoom in I only markers and not the polygons. Is there a way to use clusterOptions but still show the polygons when zooming in?

To cut a long story short, you could simply create a SpatialPointsDataFrame from the polygon data (as you did above using coordinates) and subsequently display points and polygons on the same map. Here is an example using the mapview package.
library(sp)
library(mapview)
## create spatial points from Switzerland administrative borders
gadmCHE_pts <- SpatialPointsDataFrame(coordinates(gadmCHE),
data = gadmCHE#data,
proj4string = CRS(proj4string(gadmCHE)))
## display data
mapview(gadmCHE_pts, clusterOptions = markerClusterOptions()) +
gadmCHE

Related

Locking the zoom in on Mapview?

I am creating a map plotted with points around the UK map with map view library in R. I want to have a fixed zoom or zoom button disabled. I don't want a Street view/Zoom in due to GDPR issues. I wonder if there is a solution for this? Thanks.
library(sf)
library(mapview)
mapview(datamap, xcol = "Longitude", ycol = "Latitude")
This is not possible with mapview and kinda defeats the purpose of the package. If you want this type of behaviour you either need to create the complete map using leaflet or at least create the base map with leaflet and then use it with mapview:
library(mapview)
library(leaflet)
map = leaflet(options = leafletOptions(minZoom = 12, maxZoom = 12)) %>%
addTiles()
mapview(franconia, map = map)

Crosstalk: filter Polylines in Leaflet

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?
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
As previously mentioned by Bhaskar Karambelkar:
"crosstalk for now works only with markers and not polylines/polygons"
I hope this changes soon.

R / leaflet - drawing numerous polygons

I am trying to draw numerous polygons with the leaflet package but I can't understand what's going wrong.
The shapefile I use can be found here: https://www.data.gouv.fr/en/datasets/fond-de-carte-des-codes-postaux/
library(leaflet)
library(rgdal)
df <- readOGR("C:/Users/me/codes_postaux","codes_postaux_region")
plot(df)
The shapefile seems ok to me and the code I use is rather simple. However I only get the map as an output and no Polygons. I've been struggling with this issue for quite a long time, I would really appreciate if someone could help me here.
map <- leaflet(df) %>%
addProviderTiles("CartoDB.Positron")%>%
fitBounds(10,38,10,55) %>%
addPolygons(fillOpacity = 0.8, color = "Blue", weight = 1)
map
Look at df#proj4string and the output of plot(df); axis(1); axis(2). Your shapefile uses a specific CRS. You need to transform your SpatialPolygonsDataFrame with a common CRSobj (I got the CRS code from here: Leaflet for R: Raster Images).
library(sp)
pj <- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
df2 <- spTransform(df, pj)
map2 <- leaflet(df2) %>%
addProviderTiles("CartoDB.Positron")%>%
fitBounds(10,38,10,55) %>%
addPolygons(fillOpacity = 0.8, color = "Blue", weight = 1)
map2

R Leaflet change layer order

I'm trying to produce a leaflet map in R with a layer (e.g. WMS tile or raster) and some circles. Since there are many circles in my application, I need to change the order, i.e. the layer should be shown on top of the circles.
Is there a way in R to change the order such that I can bring the WMS tile to the front or sent the circles to the background?
My code looks like the following (in a simplified way):
library(leaflet)
leaflet() %>% addTiles() %>% setView(-93.65, 42.0285, zoom = 4) %>%
addCircles(lng=-98,lat=40,radius=100000,color = "red",stroke=FALSE,fillOpacity=1) %>%
addWMSTiles(
baseUrl="http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi",
layers ="nexrad-n0r-900913",
options = WMSTileOptions(format = "image/png", transparent = TRUE),
attribution = "Weather data © 2012 IEM Nexrad"
)

tooltip for htmlwidget leaflet in R

I'm using the wonderful leaflet package in R and I'm wondering if there is a way to have a tooltip such that:
1- the user could draw a rectangle and
2- the code could estimate the actual physical size of the rectangle (in, say, feet) given the zoom level of the map and legs of the tooltip rect
## This doesn't work and mixes metaphors from leaflet and ggvis
## It's just pseudocode to give intuition
library(leaflet)
library(ggvis)
lb <- linked_brush()
map <- leaflet() %>% addTiles() %>% addCircleMarkers() %>% lb()
size <- lb()$rect_width * lb()$rect_height * map$zoom_factor

Resources