Skip to content

Instantly share code, notes, and snippets.

@jcheng5
Created March 4, 2019 00:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcheng5/53f77112d4903482c6a4c99893abd4c0 to your computer and use it in GitHub Desktop.
Save jcheng5/53f77112d4903482c6a4c99893abd4c0 to your computer and use it in GitHub Desktop.
# BE SURE TO set your Mapbox access token with:
# options(mapbox.accessToken = "...")
library(htmltools)
library(leaflet)
mapboxgl_deps <- list(
htmlDependency(
"mapbox-gl-js", "0.53.0", c(href = "https://api.mapbox.com/mapbox-gl-js/v0.53.0/"),
script = "mapbox-gl.js",
stylesheet = "mapbox-gl.css"
),
htmlDependency(
"mapbox-gl-leaflet", "0.0.3", c(href = "https://unpkg.com/mapbox-gl-leaflet@0.0.3/"),
script = "leaflet-mapbox-gl.js"
)
)
#' @export
mapboxOptions <- function(accessToken = getOption("mapbox.accessToken"),
style = NULL, ...) {
opts <- list(
accessToken = accessToken,
style = style
)
# Filter out NULL
opts[!vapply(opts, is.null, logical(1))]
}
#' @export
addMapboxGL <- function(map, options) {
if (is.null(options[["accessToken"]])) {
accessToken <- getOption("mapbox.accessToken")
if (is.null(accessToken)) {
stop("Please supply addMapboxGL() with a Mapbox access token, either via `options(mapbox.accessToken = \"...\")` or directly on the options argument.")
}
options$accessToken <- accessToken
}
map$dependencies <- c(
map$dependencies,
mapboxgl_deps
)
map <- htmlwidgets::onRender(map, "function(el, x, options) {
debugger;
L.mapboxGL(options).addTo(this);
}", options)
map
}
# Example
leaflet(quakes) %>%
addMapboxGL(options = mapboxOptions(
style = "mapbox://styles/mapbox/light-v9"
)) %>%
addMarkers()
@Thirdhuman
Copy link

Thirdhuman commented Apr 2, 2019

how would I add layer control to these objects? I'm unable to assign these to groups.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment