### Get static tiles and use with tmap Source: https://github.com/walkerke/mapboxapi/blob/master/docs/reference/get_static_tiles.html This example demonstrates how to fetch static Mapbox tiles for a given New York City tract and display them as a basemap using the tmap package. It requires the mapboxapi, tigris, and tmap libraries. ```R library(mapboxapi) library(tigris) library(tmap) library(ggspatial) library(ggplot2) ny_tracts <- tracts("NY", "New York", cb = TRUE) ny_tiles <- get_static_tiles( location = ny_tracts, zoom = 10, style_id = "light-v9", username = "mapbox" ) # tmap usage: tm_shape(ny_tiles) + tm_rgb() + tm_shape(ny_tracts) + tm_polygons(alpha = 0.5, col = "navy") + tm_credits("Basemap (c) Mapbox, (c) OpenStreetMap", position = c("RIGHT", "BOTTOM") ) ``` -------------------------------- ### Example: Creating and Publishing an MTS Tileset Source: https://github.com/walkerke/mapboxapi/blob/master/docs/reference/mts_get_recipe.html This comprehensive example demonstrates the full workflow of creating an MTS tileset. It includes fetching data with tidycensus, creating sources, defining recipe layers with specific options, validating and creating the recipe, building the tileset, publishing it, and updating the recipe if necessary. Ensure you replace 'your_mapbox_username' with your actual Mapbox username. ```R if (FALSE) { # \dontrun{ library(tidycensus) library(mapboxapi) options(tigris_use_cache = TRUE) # Get the national data on median age us_median_age_tract <- get_acs( geography = "tract", variables = "B01002_001", state = c(state.abb, "DC"), year = 2020, geometry = TRUE ) # Get it for counties as well us_median_age_county <- get_acs( geography = "county", variables = "B01002_001", year = 2020, geometry = TRUE ) # Create a source from the datasets mts_create_source(data = us_median_age_tract, tileset_id = "us_median_age_tract", username = "your_mapbox_username") mts_create_source(data = us_median_age_county, tileset_id = "us_median_age_county", username = "your_mapbox_username") # Build out the recipe. First, create a recipe layer with # appropriate options. We'll want a larger tile size and to restrict the minzoom # to 4; a maxzoom of 12 will be fine as we can overzoom beyond that # # Your source ID will be returned by `mts_create_source()`, so use that value tract_layer <- recipe_layer( source = "mapbox://tileset-source/your_mapbox_username/us_median_age_tract", minzoom = 4, maxzoom = 12, tiles = tile_options(layer_size = 2500) ) county_layer <- recipe_layer( source = "mapbox://tileset-source/your_mapbox_username/us_median_age_county", minzoom = 2, maxzoom = 5 ) recipe <- mts_make_recipe(tracts = tract_layer, counties = county_layer) # Validate the recipe mts_validate_recipe(recipe) # Create a tileset from the recipe mts_create_tileset(tileset_name = "median_age_acs", username = "your_mapbox_username", recipe = recipe) # Publish the tileset mts_publish_tileset(tileset_name = "median_age_acs", username = "your_mapbox_username") # If necessary, update the recipe mts_update_recipe(tileset_name = "median_age_acs", username = "your_mapbox_username", recipe = new_recipe) # Publish the tileset again after you've updated the recipe mts_publish_tileset(tileset_name = "median_age_acs", username = "your_mapbox_username") } # } ``` -------------------------------- ### Example: Creating MTS Tilesets with Recipe Layers Source: https://github.com/walkerke/mapboxapi/blob/master/docs/reference/feature_options.html This example demonstrates how to fetch US Census data, create Mapbox tileset sources, define recipe layers with specific options (including tile size and zoom levels), and then build and validate an MTS recipe. It shows a practical application of feature options within the mapboxapi workflow. ```R if (FALSE) { # \dontrun{ library(tidycensus) library(mapboxapi) options(tigris_use_cache = TRUE) # Get the national data on median age us_median_age_tract <- get_acs( geography = "tract", variables = "B01002_001", state = c(state.abb, "DC"), year = 2020, geometry = TRUE ) # Get it for counties as well us_median_age_county <- get_acs( geography = "county", variables = "B01002_001", year = 2020, geometry = TRUE ) # Create a source from the datasets mts_create_source(data = us_median_age_tract, tileset_id = "us_median_age_tract", username = "your_mapbox_username") mts_create_source(data = us_median_age_county, tileset_id = "us_median_age_county", username = "your_mapbox_username") # Build out the recipe. First, create a recipe layer with # appropriate options. We'll want a larger tile size and to restrict the minzoom # to 4; a maxzoom of 12 will be fine as we can overzoom beyond that # # Your source ID will be returned by `mts_create_source()`, so use that value tract_layer <- recipe_layer( source = "mapbox://tileset-source/your_mapbox_username/us_median_age_tract", minzoom = 4, maxzoom = 12, tiles = tile_options(layer_size = 2500) ) county_layer <- recipe_layer( source = "mapbox://tileset-source/your_mapbox_username/us_median_age_county", minzoom = 2, maxzoom = 5 ) recipe <- mts_make_recipe(tracts = tract_layer, counties = county_layer) # Validate the recipe mts_validate_recipe(recipe) # Create a tileset from the recipe mts_create_tileset(tileset_name = "median_age_acs", username = "your_mapbox_username", ``` -------------------------------- ### Install Mapbox Access Token Source: https://github.com/walkerke/mapboxapi/blob/master/docs/reference/mb_access_token.html Installs a Mapbox access token into your .Renviron file for persistent use across R sessions. Ensure you replace '...' with your actual Mapbox token. ```r if (FALSE) { # \dontrun{ my_token <- "..." # The token generated from your Mapbox account mb_access_token(my_token, install = TRUE) Sys.getenv("MAPBOX_PUBLIC_TOKEN") get_mb_access_token() } # } ``` -------------------------------- ### Render Vector Tiles with tippecanoe and Upload to Mapbox Source: https://github.com/walkerke/mapboxapi/blob/master/README.md This example shows how to use `tippecanoe` to render large datasets as scalable vector tiles and then upload them to a Mapbox account. This requires `tippecanoe` to be installed separately and a Mapbox secret access token to be set as an environment variable. ```r library(mapboxapi) library(mapdeck) library(httr) # Get the Microsoft buildings data for Texas and unzip GET("https://usbuildingdata.blob.core.windows.net/usbuildings-v1-1/Texas.zip", write_disk("Texas.zip", overwrite = TRUE), progress()) unzip("Texas.zip") # Use tippecanoe to make a dynamic .mbtiles file that visualizes large data appropriately # at any zoom level. sf objects can also be used as input! # (requires installing tippecanoe on your machine separately first) tippecanoe(input = "Texas.geojson", output = "Texas.mbtiles", layer_name = "texas_buildings") # Upload the generated tileset to your Mapbox account (requires a Mapbox secret access token # to be set as an environment variable) upload_tiles(input = "Texas.mbtiles", username = "kwalkertcu", tileset_id = "TX_buildings", multipart = TRUE) # Head over to Mapbox Studio when the upload is done (check the status with # `check_upload_status()`) and add it to a style. When you've styled it, bring it back # into R with mapdeck by referencing the style ID: mapdeck(token = Sys.getenv("MAPBOX_PUBLIC_TOKEN"), style = "mapbox://styles/kwalkertcu/ckaf9qxim1pyk1io7r2e8exj2/draft", zoom = 6, location = c(-98.7382803, 31.7678448)) ``` -------------------------------- ### Install mapboxapi Package Source: https://github.com/walkerke/mapboxapi/blob/master/docs/index.html Install the mapboxapi package from CRAN. This is the first step to using the package's functionalities. ```r install.packages("mapboxapi") ``` -------------------------------- ### Optimized Route Example Source: https://github.com/walkerke/mapboxapi/blob/master/docs/reference/mb_optimized_route.html Demonstrates how to use mb_optimized_route to find an optimized route for a set of coordinates. Requires the mapboxapi and sf packages. This example is wrapped in a \`dontrun\` block and requires an active Mapbox access token. ```R if (FALSE) { # \dontrun{ library(mapboxapi) library(sf) to_visit <- data.frame( X = c(-0.209307, -0.185875, -0.216877, -0.233511, -0.234541), Y = c(51.490076, 51.502113, 51.487718, 51.477418, 51.478118) ) # Convert to sf object waypoints <- st_as_sf(to_visit, coords = c("X", "Y"), crs = 4326) # Get an optimized route route <- mb_optimized_route(waypoints) # View the route geometry print(route) } ``` -------------------------------- ### EPSG:3857 Projection Setup Source: https://github.com/walkerke/mapboxapi/blob/master/docs/img/isochrone.html Initializes the EPSG:3857 (Web Mercator) projection with its associated transformation matrix. ```javascript code:"EPSG:3857",projection:di,transformation:function(){var t=.5/(Math.PI*di.R);return S(t,.5,-t, ``` -------------------------------- ### Query Tiles Example Source: https://github.com/walkerke/mapboxapi/blob/master/docs/reference/query_tiles.html This example demonstrates how to use the `query_tiles` function to retrieve contour elevation data for a specific location. It shows how to set the location, tileset ID, layer, and limit, and how to extract the maximum elevation from the results. ```R if (FALSE) { # \dontrun! { library(mapboxapi) elevation <- query_tiles( location = "Breckenridge, Colorado", tileset_id = "mapbox.mapbox-terrain-v2", layer = "contour", limit = 50 ) max(elevation$features$properties$ele) } # } ``` -------------------------------- ### Basic Isochrone Request Source: https://github.com/walkerke/mapboxapi/blob/master/docs/img/isochrone.html A simple example demonstrating how to make a request to the Isochrone API to get reachable areas within a specified time. ```javascript mapboxgl.Mapbox.prototype.getIsochrone = function(options, callback) { var url = "https://api.mapbox.com/isochrone/v1/"; var accessToken = this.getAccessToken(); if (!accessToken) { throw new Error("Mapbox access token not found. Please set it using mapboxgl.accessToken."); } var query = [ options.profile || 'driving-traffic', options.longitude + ',' + options.latitude ].join('/'); var params = [ 'contours_minutes=' + (options.contours_minutes || '10,20,30'), 'polygons=true', 'denoise=true' ].join('&'); var requestUrl = url + query + '?' + params + '&access_token=' + accessToken; fetch(requestUrl) .then(response => { if (!response.ok) { throw new Error('Network response was not ok ' + response.statusText); } return response.json(); }) .then(data => { if (callback) { callback(null, data); } }) .catch(error => { if (callback) { callback(error, null); } }); }; // Example Usage: // map.getIsochrone({ // profile: 'walking', // longitude: -77.032384, // latitude: 38.913188, // contours_minutes: [5, 10, 15] // }, function(err, data) { // if (err) throw err; // console.log(data); // // Add GeoJSON data to the map // map.addSource('isochrone', { // 'type': 'geojson', // 'data': data // }); // map.addLayer({ // 'id': 'isochrone-fill', // 'type': 'fill', // 'source': 'isochrone', // 'layout': {}, // 'paint': { // 'fill-color': '#007cbf', // 'fill-opacity': 0.5 // } // }); // }); ``` -------------------------------- ### mb_access_token Source: https://github.com/walkerke/mapboxapi/blob/master/docs/reference/mb_access_token.html Installs or retrieves a Mapbox access token. It can optionally overwrite an existing token and install the token in your .Renviron file for future use. ```APIDOC ## mb_access_token ### Description Installs or retrieves a Mapbox access token. It can optionally overwrite an existing token and install the token in your .Renviron file for future use. ### Usage ```R mb_access_token(token, overwrite = FALSE, install = FALSE) ``` ### Arguments * **token** (string) - A Mapbox access token; can be public (starting with 'pk') or secret (starting with 'sk') scope, which the function will interpret for you. * **overwrite** (boolean) - Whether or not to overwrite an existing Mapbox access token. Defaults to `FALSE`. * **install** (boolean) - If `TRUE`, will install the key in your `.Renviron` file for use in future sessions. Defaults to `FALSE`. ### Examples ```R # Example of installing a token and checking .Renviron # my_token <- "..." # Replace with your actual token # mb_access_token(my_token, install = TRUE) # Sys.getenv("MAPBOX_PUBLIC_TOKEN") ``` ``` -------------------------------- ### Get static tiles and use with ggplot2 Source: https://github.com/walkerke/mapboxapi/blob/master/docs/reference/get_static_tiles.html This example shows how to retrieve static Mapbox tiles for a New York City tract and overlay it with spatial data using ggplot2 and ggspatial. Ensure mapboxapi, tigris, and ggplot2 libraries are loaded. ```R library(mapboxapi) library(tigris) library(tmap) library(ggspatial) library(ggplot2) ny_tracts <- tracts("NY", "New York", cb = TRUE) ny_tiles <- get_static_tiles( location = ny_tracts, zoom = 10, style_id = "light-v9", username = "mapbox" ) # ggplot2 usage: ggplot() + layer_spatial(ny_tiles) + geom_sf(data = ny_tracts, fill = "navy", alpha = 0.5) + theme_void() + labs(caption = "Basemap (c) Mapbox, (c) OpenStreetMap") ``` -------------------------------- ### Install and Set Mapbox Access Token Source: https://github.com/walkerke/mapboxapi/blob/master/README.md Install the package from CRAN and set your Mapbox access token for use within the package. A public or secret token can be stored. ```r install.packages("mapboxapi") # For the development version: # remotes::install_github("walkerke/mapboxapi") # Get your access token from your Mapbox account and save it in R; save a public token, # secret token, or both with successive calls to mb_access_token() mapboxapi::mb_access_token("pk.eyzdl....", install = TRUE) ``` -------------------------------- ### Enable Drag Start Globally Source: https://github.com/walkerke/mapboxapi/blob/master/docs/img/isochrone.html Globally enables the default browser drag start behavior. This is the default behavior. ```javascript function Tt(){ q(window,"dragstart",$) } ``` -------------------------------- ### HTML Widgets Event Listener Setup Source: https://github.com/walkerke/mapboxapi/blob/master/docs/img/isochrone.html Sets up event listeners for various widget events to trigger a resize handler. Includes specific handling for ioslides. ```javascript var resizeHandler = function() { // Placeholder for actual resize logic }; if (window.addEventListener) { // Standard event listeners window.jQuery(document).on( "shown.htmlwidgets shown.bs.tab.htmlwidgets shown.bs.collapse.htmlwidgets", resizeHandler ); window.jQuery(document).on( "hidden.htmlwidgets hidden.bs.tab.htmlwidgets hidden.bs.collapse.htmlwidgets", resizeHandler ); // ioslides specific event listeners if (window.addEventListener) { on(document, "slideenter", resizeHandler); on(document, "slideleave", resizeHandler); } } ``` -------------------------------- ### Projection Initialization Source: https://github.com/walkerke/mapboxapi/blob/master/docs/img/isochrone.html Initializes the projection system by setting up the necessary projection objects. This is typically called once at the start of the application. ```javascript Projection.projections=f,Projection.projections.start() ``` -------------------------------- ### Set Mapbox Access Token Source: https://github.com/walkerke/mapboxapi/blob/master/docs/index.html Set your Mapbox access token for use within the package. The 'install = TRUE' argument saves the token for future sessions. ```r library(mapboxapi) mb_access_token("pk.eyas...", install = TRUE) ``` -------------------------------- ### Error when hello function is not found Source: https://github.com/walkerke/mapboxapi/blob/master/docs/reference/hello.html This example demonstrates the error message received when the 'hello' function is not defined or loaded in the R session. ```r #> Error in hello(): could not find function "hello" ``` -------------------------------- ### Create and Plot a Walking Isochrone Source: https://github.com/walkerke/mapboxapi/blob/master/docs/index.html This example demonstrates how to generate a 5-minute walking isochrone from a given address and display it on an interactive Leaflet map using Mapbox tiles. ```r library(leaflet) walk_5min <- mb_isochrone("2850 S University Dr, Fort Worth TX 76129", profile = "walking", time = 5) leaflet(walk_5min) %>% addMapboxTiles(style_id = "streets-v11", username = "mapbox") %>% addPolygons() ``` -------------------------------- ### Initialize Mapbox GL JS Map Source: https://github.com/walkerke/mapboxapi/blob/master/docs/img/isochrone.html Basic setup for initializing a Mapbox GL JS map with a specified style and center coordinates. ```javascript mapboxgl.accessToken = 'YOUR_MAPBOX_ACCESS_TOKEN'; const map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/streets-v11', center: [-74.5, 40], zoom: 9 }); ``` -------------------------------- ### List tilesets in a Mapbox account Source: https://github.com/walkerke/mapboxapi/blob/master/docs/reference/mts_list_tilesets.html Retrieves a list of all tilesets associated with a given Mapbox username. This example is wrapped in a conditional to prevent execution during package checks. ```r if (FALSE) { # \dontrun{ tileset_list <- mts_list_tilesets(username = "your_mapbox_username") } # } ``` -------------------------------- ### Example: Full Tileset Publishing Workflow Source: https://github.com/walkerke/mapboxapi/blob/master/docs/reference/mts_publish_tileset.html Demonstrates the complete process of creating, configuring, and publishing a tileset. This includes fetching data, creating sources, defining recipes, validating, creating, and publishing the tileset. ```r if (FALSE) { # \dontrun{ library(tidycensus) library(mapboxapi) options(tigris_use_cache = TRUE) # Get the national data on median age us_median_age_tract <- get_acs( geography = "tract", variables = "B01002_001", state = c(state.abb, "DC"), year = 2020, geometry = TRUE ) # Get it for counties as well us_median_age_county <- get_acs( geography = "county", variables = "B01002_001", year = 2020, geometry = TRUE ) # Create a source from the datasets mts_create_source(data = us_median_age_tract, tileset_id = "us_median_age_tract", username = "your_mapbox_username") mts_create_source(data = us_median_age_county, tileset_id = "us_median_age_county", username = "your_mapbox_username") # Build out the recipe. First, create a recipe layer with # appropriate options. We'll want a larger tile size and to restrict the minzoom # to 4; a maxzoom of 12 will be fine as we can overzoom beyond that # # Your source ID will be returned by `mts_create_source()`, so use that value tract_layer <- recipe_layer( source = "mapbox://tileset-source/your_mapbox_username/us_median_age_tract", minzoom = 4, maxzoom = 12, tiles = tile_options(layer_size = 2500) ) county_layer <- recipe_layer( source = "mapbox://tileset-source/your_mapbox_username/us_median_age_county", minzoom = 2, maxzoom = 5 ) recipe <- mts_make_recipe(tracts = tract_layer, counties = county_layer) # Validate the recipe mts_validate_recipe(recipe) # Create a tileset from the recipe mts_create_tileset(tileset_name = "median_age_acs", username = "your_mapbox_username", recipe = recipe) # Publish the tileset mts_publish_tileset(tileset_name = "median_age_acs", username = "your_mapbox_username") # If necessary, update the recipe mts_update_recipe(tileset_name = "median_age_acs", username = "your_mapbox_username", recipe = new_recipe) # Publish the tileset again after you've updated the recipe mts_publish_tileset(tileset_name = "median_age_acs", username = "your_mapbox_username") } # } ``` -------------------------------- ### Tile Layer Initialization and Options Source: https://github.com/walkerke/mapboxapi/blob/master/docs/img/isochrone.html Demonstrates the initialization of a tile layer with various configuration options. Key options include `tileSize`, `opacity`, `updateWhenIdle`, and `className`. ```javascript var _n = Ue.extend({ options: { tileSize: 256, opacity: 1, updateWhenIdle: ji, updateWhenZooming: !0, updateInterval: 200, zIndex: 1, bounds: null, minZoom: 0, maxZoom: void 0, maxNativeZoom: void 0, minNativeZoom: void 0, noWrap: !1, pane: "tilePane", className: "", keepBuffer: 2 }, initialize: function(t) { l(this, t) }, onAdd: function() { this._initContainer(), this._levels = {}, this._tiles = {}, this._resetView(), this._update() }, beforeAdd: function(t) { t._addZoomLimit(this) }, onRemove: function(t) { this._removeAllTiles(), ut(this._container), t._removeZoomLimit(this), this._container = null, this._tileZoom = void 0 }, bringToFront: function() { return this._map && (ct(this._container), this._setAutoZIndex(Math.max)), this }, bringToBack: function() { return this._map && (_t(this._container), this._setAutoZIndex(Math.min)), this }, getContainer: function() { return this._container }, setOpacity: function(t) { return this.options.opacity = t, this._updateOpacity(), this }, setZIndex: function(t) { return this.options.zIndex = t, this._updateZIndex(), this }, isLoading: function() { return this._loading }, redraw: function() { return this._map && (this._removeAllTiles(), this._update()), this }, getEvents: function() { var t = { viewprereset: this._invalidateAll, viewreset: this._resetView, zoom: this._resetView, moveend: this._onMoveEnd }; return this.options.updateWhenIdle || (this._onMove || (this._onMove = o(this._onMoveEnd, this.options.updateInterval, this)), t.move = this._onMove), this._zoomAnimated && (t.zoomanim = this._animateZoom), t }, createTile: function() { return document.createElement("div") }, getTileSize: function() { var t = this.options.tileSize; return t instanceof x ? t : new x(t, t) }, _updateZIndex: function() { this._container && void 0 !== this.options.zIndex && null !== this.options.zIndex && (this._container.style.zIndex = this.options.zIndex) }, _setAutoZIndex: function(t) { for (var i, e = this.getPane().children, n = -t(-1 / 0, 1 / 0), o = 0, s = e.length; o < s; o++) i = e[o].style.zIndex, e[o] !== this._container && i && (n = t(n, +i)); isFinite(n) && (this.options.zIndex = n + t(-1, 1), this._updateZIndex()) }, _updateOpacity: function() { if (this._map && !Li) { vt(this._container, this.options.opacity); var t = +new Date, i = !1, e = !1; for (var n in this._tiles) { var o = this._tiles[n]; if (o.current && o.loaded) { var s = Math.min(1, (t - o.loaded) / 200); vt(o.el, s), s < 1 ? i = !0 : (o.active ? e = !0 : this._onOpaqueTile(o), o.active = !0) } } e && !this._noPrune && this._pruneTiles(), i && (g(this._fadeFrame), this._fadeFrame = f(this._updateOpacity, this)) } }, _onOpaqueTile: r, _initContainer: function() { this._container || (this._container = ht("div", "leaflet-layer " + (this.options.className || "")), this._updateZIndex(), this.options.opacity < 1 && this._updateOpacity(), this.getPane().appendChild(this._container)) }, _updateLevels: function() { var t = this._tileZoom, i = this.options.maxZoom; if (void 0 !== t) { for (var e in this._levels) this._levels[e].el.children.length || e === t ? (this._levels[e].el.style.zIndex = i - Math.abs(t - e), this._onUpdateLevel(e)) : (ut(this._levels[e].el), this._removeTilesAtZoom(e), this._onRemoveLevel(e), delete this._levels[e]) var n = this._levels[t]; return n || ((n = this._levels[t] = {}).el = ht("div", "leaflet-tile-container leaflet-zoom-animated", this._container), n.el.style.zIndex = i, n.zoom = t, this._setZoomTransform(n, this._map.getCenter(), this._map.getZoom()), n.el.offsetWidth, this._onCreat ``` -------------------------------- ### Create Mapbox Tiling Service Recipe Source: https://github.com/walkerke/mapboxapi/blob/master/docs/reference/mts_make_recipe.html This example demonstrates how to create a Mapbox Tiling Service recipe using `mts_make_recipe`. It involves fetching data, creating sources, defining recipe layers with specific zoom levels and tile options, and finally creating and publishing a tileset. ```R library(tidycensus) library(mapboxapi) options(tigris_use_cache = TRUE) # Get the national data on median age us_median_age_tract <- get_acs( geography = "tract", variables = "B01002_001", state = c(state.abb, "DC"), year = 2020, geometry = TRUE ) # Get it for counties as well us_median_age_county <- get_acs( geography = "county", variables = "B01002_001", year = 2020, geometry = TRUE ) # Create a source from the datasets mts_create_source(data = us_median_age_tract, tileset_id = "us_median_age_tract", username = "your_mapbox_username") mts_create_source(data = us_median_age_county, tileset_id = "us_median_age_county", username = "your_mapbox_username") # Build out the recipe. First, create a recipe layer with # appropriate options. We'll want a larger tile size and to restrict the minzoom # to 4; a maxzoom of 12 will be fine as we can overzoom beyond that # # Your source ID will be returned by `mts_create_source()`, so use that value tract_layer <- recipe_layer( source = "mapbox://tileset-source/your_mapbox_username/us_median_age_tract", minzoom = 4, maxzoom = 12, tiles = tile_options(layer_size = 2500) ) county_layer <- recipe_layer( source = "mapbox://tileset-source/your_mapbox_username/us_median_age_county", minzoom = 2, maxzoom = 5 ) recipe <- mts_make_recipe(tracts = tract_layer, counties = county_layer) # Validate the recipe mts_validate_recipe(recipe) # Create a tileset from the recipe mts_create_tileset(tileset_name = "median_age_acs", username = "your_mapbox_username", recipe = recipe) # Publish the tileset mts_publish_tileset(tileset_name = "median_age_acs", username = "your_mapbox_username") # If necessary, update the recipe mts_update_recipe(tileset_name = "median_age_acs", username = "your_mapbox_username", recipe = new_recipe) # Publish the tileset again after you've updated the recipe mts_publish_tileset(tileset_name = "median_age_acs", username = "your_mapbox_username") ``` -------------------------------- ### Tile Layer Initialization and Options Source: https://github.com/walkerke/mapboxapi/blob/master/docs/img/isochrone.html Initializes a tile layer with URL, options, and handles retina detection. Sets up event listeners for tile loading and unloading. ```javascript dn=_n.extend({options:{minZoom:0,maxZoom:18,subdomains:"abc",errorTileUrl:"",zoomOffset:0,tms:!1,zoomReverse:!1,detectRetina:!1,crossOrigin:!1},initialize:function(t,i){this._url=t;(i=l(this,i)).detectRetina&&Ki&&i.maxZoom>0&&(i.tileSize=Math.floor(i.tileSize/2),i.zoomReverse?(i.zoomOffset--,i.minZoom++):(i.zoomOffset++,i.maxZoom--),i.minZoom=Math.max(0,i.minZoom)),"string"==typeof i.subdomains&&(i.subdomains=i.subdomains.split("")),Ti||this.on("tileunload",this._onTileRemove)},setUrl:function(t,i){return this._url=t,i||this.redraw(),this},createTile:function(t,i){var n=document.createElement("img");return V(n,"load",e(this._tileOnLoad,this,i,n)),V(n,"error",e(this._tileOnError,this,i,n)),this.options.crossOrigin&&(n.crossOrigin=""),n.alt="",n.setAttribute("role","presentation"),n.src=this.getTileUrl(t),n},getTileUrl:function(t){var e={r:Ki?"@2x":"",s:this._getSubdomain(t),x:t.x,y:t.y,z:this._getZoomForUrl()};if(this._map&&!this._map.options.crs.infinite){var n=this._globalTileRange.max.y-t.y;this.options.tms&&(e.y=n),e["-y"]=n}return _(this._url,i(e,this.options))},_tileOnLoad:function(t,i){Li?setTimeout(e(t,this,null,i),0):t(null,i)},_tileOnError:function(t,i,e){var n=this.options.errorTileUrl;n&&i.getAttribute("src")!==n&&(i.src=n),t(e,i)},_onTileRemove:function(t){t.tile.onload=null},_getZoomForUrl:function(){var t=this._tileZoom,i=this.options.maxZoom,e=this.options.zoomReverse,n=this.options.zoomOffset;return e&&(t=i-t),t+n},_getSubdomain:function(t){var i=Math.abs(t.x+t.y)%this.options.subdomains.length;return this.options.subdomains[i]},_abortLoading:function(){var t,i;for(t in this._tiles)this._tiles[t].coords.z!==this._tileZoom&&((i=this._tiles[t].el).onload=r,i.onerror=r,i.complete||(i.src=ni,ut(i),delete this._tiles[t]))}}) ``` -------------------------------- ### Get Element by ID Source: https://github.com/walkerke/mapboxapi/blob/master/docs/img/isochrone.html A utility function to get a DOM element by its ID, or return the element itself if already provided. ```javascript function rt(t){ return "string"==typeof t?document.getElementById(t):t } ``` -------------------------------- ### Create and Publish a Mapbox Tileset Source: https://github.com/walkerke/mapboxapi/blob/master/docs/reference/mts_create_tileset.html This example demonstrates the complete workflow of creating a Mapbox tileset from ACS data. It includes creating data sources, building a recipe, validating it, creating the tileset, and publishing it. Ensure you replace 'your_mapbox_username' with your actual Mapbox username. ```R if (FALSE) { # \dontrun{ library(tidycensus) library(mapboxapi) options(tigris_use_cache = TRUE) # Get the national data on median age us_median_age_tract <- get_acs( geography = "tract", variables = "B01002_001", state = c(state.abb, "DC"), year = 2020, geometry = TRUE ) # Get it for counties as well us_median_age_county <- get_acs( geography = "county", variables = "B01002_001", year = 2020, geometry = TRUE ) # Create a source from the datasets mts_create_source(data = us_median_age_tract, tileset_id = "us_median_age_tract", username = "your_mapbox_username") mts_create_source(data = us_median_age_county, tileset_id = "us_median_age_county", username = "your_mapbox_username") # Build out the recipe. First, create a recipe layer with # appropriate options. We'll want a larger tile size and to restrict the minzoom # to 4; a maxzoom of 12 will be fine as we can overzoom beyond that # # Your source ID will be returned by `mts_create_source()`, so use that value tract_layer <- recipe_layer( source = "mapbox://tileset-source/your_mapbox_username/us_median_age_tract", minzoom = 4, maxzoom = 12, tiles = tile_options(layer_size = 2500) ) county_layer <- recipe_layer( source = "mapbox://tileset-source/your_mapbox_username/us_median_age_county", minzoom = 2, maxzoom = 5 ) recipe <- mts_make_recipe(tracts = tract_layer, counties = county_layer) # Validate the recipe mts_validate_recipe(recipe) # Create a tileset from the recipe mts_create_tileset(tileset_name = "median_age_acs", username = "your_mapbox_username", recipe = recipe) # Publish the tileset mts_publish_tileset(tileset_name = "median_age_acs", username = "your_mapbox_username") # If necessary, update the recipe mts_update_recipe(tileset_name = "median_age_acs", username = "your_mapbox_username", recipe = new_recipe) # Publish the tileset again after you've updated the recipe mts_publish_tileset(tileset_name = "median_age_acs", username = "your_mapbox_username") } # } ``` -------------------------------- ### Disable Drag Start Globally Source: https://github.com/walkerke/mapboxapi/blob/master/docs/img/isochrone.html Globally disables the default browser drag start behavior. Useful for preventing unwanted image dragging. ```javascript function bt(){ V(window,"dragstart",$) } ``` -------------------------------- ### Generate .mbtiles with tippecanoe and upload Source: https://github.com/walkerke/mapboxapi/blob/master/docs/reference/tippecanoe.html This example demonstrates a complete workflow: fetching census data, converting it to representative dots, generating an .mbtiles file using tippecanoe, and then uploading the tileset to a Mapbox account. Ensure your Mapbox access token is set using mb_access_token() before uploading. ```R if (FALSE) { # \dontrun{ # Workflow: create a dynamic tileset for dot-density mapping library(tidycensus) library(sf) library(mapboxapi) # Get population data for Census tracts in Vermont vt_population <- get_decennial( geography = "tract", variables = "P001001", state = "Vermont", year = 2010, geometry = TRUE ) # Convert to representative dots - 1 per person vt_dots <- st_sample( vt_population, size = vt_population$value ) # Use tippecanoe to create dynamic tiles tippecanoe( input = vt_dots, output = "vt_population.mbtiles", layer_name = "vermont_population", max_zoom = 18, drop_rate = 1.5 ) # Upload to your Mapbox account for visualization # A Mapbox secret access token must be set with mb_access_token() # to upload data to your account upload_tiles( input = "vt_population.mbtiles", username = "kwalkertcu", tileset_id = "vt_population_dots", multipart = TRUE ) } # } ``` -------------------------------- ### Build a Shiny Routing App with mb_directions Source: https://github.com/walkerke/mapboxapi/blob/master/README.md This example demonstrates building a Shiny application that uses `mb_directions` to calculate and display routes between two points. It includes geocoding inputs, route visualization on a map, and rendering driving instructions. ```r library(shiny) library(mapdeck) library(mapboxapi) # Set up a sidebar panel with geocoders for origin and destination, # and a placeholder to print out the driving instructions ui <- fluidPage( tags$head( tags$style(HTML( "#origin { position: relative; z-index: 999999; }" )) ), sidebarPanel( mapboxGeocoderInput("origin", placeholder = "Enter an origin", proximity = mb_geocode("Fort Worth, TX")), shiny::br(), mapboxGeocoderInput("destination", placeholder = "Enter a destination", proximity = mb_geocode("Fort Worth, TX")), shiny::br(), actionButton("action", "Show me the route!"), htmlOutput("instructions"), width = 4 ), mainPanel( mapdeckOutput(outputId = "map", width = "100%", height = 600) ) ) # Set up reactive elements to generate routes when the action button is clicked, # then map the routes and print out the driving directions server <- function(input, output) { output$map <- renderMapdeck({ mapdeck(token = Sys.getenv("MAPBOX_PUBLIC_TOKEN"), style = mapdeck_style("light"), zoom = 11, location = c(-97.3034314, 32.7593745)) }) new_route <- eventReactive(input$action, { mb_directions( input_data = rbind( geocoder_as_sf(input$origin), geocoder_as_sf(input$destination) ), profile = "driving", output = "sf", steps = TRUE ) }) observeEvent(new_route(), { mapdeck_update(map_id = "map") %>% clear_path(layer_id = "new_route") %>% add_path(data = new_route(), stroke_width = 75, layer_id = "new_route", update_view = TRUE, focus_layer = TRUE) output$instructions <- renderUI({ HTML(paste0( paste("•", new_route()$instruction, sep = ""), collapse = "
")) }) }) } shinyApp(ui = ui, server = server) ``` -------------------------------- ### Call the hello function Source: https://github.com/walkerke/mapboxapi/blob/master/docs/reference/hello.html This snippet shows how to call the 'hello' function. Ensure the function is available in your environment before calling it. ```r hello() ``` -------------------------------- ### Get Control Source: https://github.com/walkerke/mapboxapi/blob/master/docs/img/isochrone.html Retrieves a control from the map using its layer ID. ```javascript methods.getControl = function (layerId) { this.controls.get(layerId); }; ``` -------------------------------- ### Initialize Widget Sizing Source: https://github.com/walkerke/mapboxapi/blob/master/docs/img/isochrone.html Sets up element sizing and padding based on the widget's sizing policy. Handles fill, overflow, and margin/padding adjustments. ```javascript function initSizing(el) { var sizing = sizingPolicy(el); if (!sizing) return; var cel = document.getElementById("htmlwidget_container"); if (!cel) return; if (typeof(sizing.padding) !== "undefined") { document.body.style.margin = "0"; document.body.style.padding = paddingToCss(unpackPadding(sizing.padding)); } if (sizing.fill) { document.body.style.overflow = "hidden"; document.body.style.width = "100%"; document.body.style.height = "100%"; document.documentElement.style.width = "100%"; document.documentElement.style.height = "100%"; if (cel) { cel.style.position = "absolute"; var pad = unpackPadding(sizing.padding); cel.style.top = pad.top + "px"; cel.style.right = pad.right + "px"; cel.style.bottom = pad.bottom + "px"; cel.style.left = pad.left + "px"; el.style.width = "100%"; el.style.height = "100%"; } return { getWidth: function() { return cel.offsetWidth; }, getHeight: function() { return cel.offsetHeight; } }; } else { el.style.width = px(sizing.width); el.style.height = px(sizing.height); return { getWidth: function() { return el.offsetWidth; }, getHeight: function() { return el.offsetHeight; } }; } } ``` -------------------------------- ### Get GeoJSON Feature Source: https://github.com/walkerke/mapboxapi/blob/master/docs/img/isochrone.html Extracts a GeoJSON feature object from a Leaflet layer. ```javascript nn.getFeature = qt; ``` -------------------------------- ### Projection System Initialization Source: https://github.com/walkerke/mapboxapi/blob/master/docs/img/isochrone.html Initializes projection systems based on provided parameters. It handles various projection types and their associated units and datums. ```javascript function(a){function b(b){var c=a.to_meter||1;return parseFloat(b,10)*c}"GEOGCS"===a.type?a.projName="longlat":"LOCAL_CS"===a.type?(a.projName="identity",a.local=!0):"object"==typeof a.PROJECTION?a.projName=Object.keys(a.PROJECTION)[0]:a.projName=a.PROJECTION,a.UNIT&&(a.units=a.UNIT.name.toLowerCase(),"metre"===a.units&&(a.units="meter"), a.UNIT.convert&&("GEOGCS"===a.type?a.DATUM&&a.DATUM.SPHEROID&&(a.to_meter=parseFloat(a.UNIT.convert,10)*a.DATUM.SPHEROID.a):a.to_meter=parseFloat(a.UNIT.convert,10))),a.GEOGCS&&(a.GEOGCS.DATUM?a.datumCode=a.GEOGCS.DATUM.name.toLowerCase():a.datumCode=a.GEOGCS.name.toLowerCase(),"d_"===a.datumCode.slice(0,2)&&(a.dat ``` -------------------------------- ### Get Anchor Points Source: https://github.com/walkerke/mapboxapi/blob/master/docs/img/isochrone.html Retrieves the anchor points for popups and tooltips associated with the icon. ```javascript _getPopupAnchor:function(){return this.options.icon.options.popupAnchor},_getTooltipAnchor:function(){return this.options.icon.options.tooltipAnchor}} ``` -------------------------------- ### Get Bounding Box Center Source: https://github.com/walkerke/mapboxapi/blob/master/docs/img/isochrone.html Calculates and returns the center point of the bounding box. ```javascript getCenter:function(){return new M((this._southWest.lat+this._northEast.lat)/2,(this._southWest.lng+this._northEast.lng)/2)} ``` -------------------------------- ### Publish and Update Mapbox Tileset Source: https://github.com/walkerke/mapboxapi/blob/master/docs/reference/feature_options.html Demonstrates how to publish a tileset and then update its recipe before publishing again. Ensure you replace 'your_mapbox_username' with your actual Mapbox username. ```R recipe <- list( "tileset_name" = "median_age_acs", "recipe_name" = "median_age_acs", "version" = "1.0.0", "layers" = list( list( "source" = list( "type" = "vector", "url" = "mapbox://your_mapbox_username.median_age_acs" ), "destination" = list( "type" = "vector", "url" = "mapbox://your_mapbox_username.median_age_acs" ) ) ) ) # Publish the tileset mts_publish_tileset(tileset_name = "median_age_acs", username = "your_mapbox_username") # If necessary, update the recipe new_recipe <- recipe new_recipe$version <- "1.1.0" mts_update_recipe(tileset_name = "median_age_acs", username = "your_mapbox_username", recipe = new_recipe) # Publish the tileset again after you've updated the recipe mts_publish_tileset(tileset_name = "median_age_acs", username = "your_mapbox_username") ``` -------------------------------- ### Path Initialization and Rendering Source: https://github.com/walkerke/mapboxapi/blob/master/docs/img/isochrone.html Initializes path properties and handles adding/removing the path from the renderer. Supports redrawing and style updates. ```javascript beforeAdd:function(t){this._renderer=t.getRenderer(this)},onAdd:function(){this._renderer._initPath(this),this._reset(),this._renderer._addPath(this)},onRemove:function(){this._renderer._removePath(this)},redraw:function(){return this._map&&this._renderer._updatePath(this),this},setStyle:function(t){return l(this,t),this._renderer&&this._renderer._updateStyle(this),this},bringToFront:function(){return this._renderer&&this._renderer._bringToFront(this),this},bringToBack:function(){return this._renderer&&this._renderer._bringToBack(this),this},getElement:function(){return this._path}, _reset:function(){this._project(),this._update()},_clickTolerance:function(){return(this.options.stroke?this.options.weight/2:0)+this._renderer.options.tolerance}} ``` -------------------------------- ### Get Multiple CSS Properties Source: https://github.com/walkerke/mapboxapi/blob/master/docs/img/isochrone.html Retrieves the computed styles for multiple CSS properties of an element. ```javascript n.fn.extend({ css:function(a,b){ return Y(this,function(a,b,c){ var d,e,f={},g=0 if(n.isArray(b)){ for(d=0 ```