• Stars
    star
    110
  • Rank 316,770 (Top 7 %)
  • Language
    HTML
  • License
    Other
  • Created over 6 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

R interface to Mapbox web services

mapboxapi

CRAN status CRAN Downloads

An R interface to Mapbox APIs and web services

The purpose of {mapboxapi} is to facilitate the use of Mapbox web services for spatial data science tasks in R. Current and future versions of the package allow R users to return Mapbox navigation requests as simple features (sf) objects, convert R objects to Mapbox vector tilesets, and query Mapbox tilesets from R, among other tasks. The package is not a complete wrapper of the API (though new features will continually be added) nor is it an interface to Mapbox GL JS, Mapbox's web mapping API.

Install the package from CRAN then store your Mapbox access token for use in the package:

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)

More thorough documentation will be coming as I develop the package. In the meantime, take a look at the following examples:

Example 1: Building a routing app with Shiny and mb_directions()

library(shiny)
library(mapdeck)
library(mapboxapi)

# Set up a sidebar panel with text boxes for origin and destination, 
# and a placeholder to print out the driving instructions
ui <- fluidPage(
  sidebarPanel(
    textInput("origin_text", label = "Origin",
              placeholder = "Type an address or place name"),
    textInput("destination_text", label = "Destination",
              placeholder = "Type an address or place name"),
    actionButton("action", "Show me the route!"),
    htmlOutput("instructions"),
    width = 3
  ),
  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(
      origin = input$origin_text,
      destination = input$destination_text,
      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("&bull;", new_route()$instruction, sep = ""),
        collapse = "<br/>"))
    })
  })

}

shinyApp(ui = ui, server = server)

Example 2: render large datasets as scalable vector tiles with tippecanoe

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))

Example 3: a research workflow to determine how median gross rent varies by distance from downtown

library(mapboxapi)
library(tidyverse)
library(tidycensus)
library(tigris)
library(sf)
library(crsuggest)
options(tigris_use_cache = TRUE)

# Grab median gross rent data from the 2014-2018 ACS for the Twin Cities metro
county_names <- c("Hennepin", "Ramsey", "Anoka", "Washington",
                  "Dakota", "Carver", "Scott")

tc_rent <- get_acs(geography = "tract",
                   variables = "B25064_001",
                   state = "MN",
                   county = county_names,
                   geometry = TRUE)

# Find the right coordinate system to use; in this case we'll use 26993
print(suggest_top_crs(tc_rent, units = "m"))

# Remove water areas - there are a lot in Minnesota! - to help ensure that a point in a 
# given Census tract will be routable
tc_water <- county_names %>%
  map(~area_water("MN", .x)) %>%
  rbind_tigris() %>%
  mutate(pct = percent_rank(AWATER)) %>%
  filter(pct >= 0.95) %>%
  st_union() %>%
  st_transform(26993)

tc_rent_points <- tc_rent %>%
  st_transform(26993) %>%
  st_difference(tc_water) %>%
  st_point_on_surface()

# Determine the location of downtown (apologies to St. Paul, purposes of illustration here)
downtown_mpls <- mb_geocode("Minneapolis City Hall, Minneapolis MN")

# Use mb_matrix() to calculate driving time from all Twin Cities Census tracts to downtown
time_to_downtown <- mb_matrix(origins = tc_rent_points,
                              destinations = downtown_mpls) %>%
  as.vector()

tc_rent$time <- time_to_downtown

# Visualize how rent varies by travel time from downtown with ggplot2
ggplot(tc_rent, aes(x = time, y = estimate)) +
  geom_smooth() +
  scale_y_continuous(labels = scales::dollar) +
  labs(x = "Travel time to downtown Minneapolis (in minutes)",
       y = "Median gross rent in Census tract", 
       title = "Median rent by drive-time to downtown Minneapolis",
       subtitle = "Census tracts in the seven-county Twin Cities metropolitan area",
       caption = "Data sources: Mapbox Directions API, 2014-2018 ACS") + 
  theme_minimal()

More Repositories

1

tidycensus

Load US Census boundary and attribute data as 'tidyverse' and 'sf'-ready data frames in R
R
638
star
2

tigris

Download and use Census TIGER/Line shapefiles in R
R
324
star
3

neighborhood_diversity

Shiny application on neighborhood diversity
R
129
star
4

crsuggest

Get appropriate CRS suggestions for your spatial data in R
R
128
star
5

pygris

Use US Census shapefiles in Python (port of the R tigris package)
Python
108
star
6

mapgl

R interface to Mapbox GL JS v3 and Maplibre GL JS
HTML
87
star
7

census-with-r-book

Source for Analyzing US Census Data: Methods, Maps, and Models in R by Kyle Walker, published with CRC Press
HTML
81
star
8

bsselectR

In-progress htmlwidget for bootstrap-select
JavaScript
61
star
9

idbr

An R interface to the US Census Bureau International Data Base API
R
58
star
10

education_map

Educational Attainment in America
HTML
51
star
11

umich-workshop-2023

Materials for ACS workshops given at SSDAN / University of Michigan in 2023
HTML
48
star
12

umich-workshop

Slides and code for tidycensus workshops given at the University of Michigan in March 2021
HTML
47
star
13

map-challenge-2023

Code and maps for 2023's 30 Day Map Challenge
HTML
43
star
14

geog30323

Materials for GEOG 30323: Data Analysis & Visualization at TCU
Jupyter Notebook
37
star
15

umich-workshop-2024

Slides and code for workshops given with the University of Michigan's SSDAN in 2024
HTML
36
star
16

umich-workshop-2022

Slides and code for Census data workshops given at the University of Michigan in 2022
JavaScript
31
star
17

mb-immigrants

HTML
24
star
18

teaching-with-datavis

Code for 'Teaching with Interactive Data Visualization' site
HTML
23
star
19

sports-geography

Materials for Sports Geography & Society, taught May Session 2018 at TCU
HTML
20
star
20

walkerke.github.io

Walker Data website
HTML
19
star
21

kwgeo

Tools for visualizing and manipulating geographic data in R
R
12
star
22

texas_pyramids

Shiny application to explore Texas county demographics
R
9
star
23

cloud-spatial-data-science

Tutorials on how to set up a spatial data science environment on Amazon EC2
TeX
9
star
24

acs14lite

Lightweight R interface to the Census API for the 2010-2014 American Community Survey
R
8
star
25

MUSAmasterclass

HTML
7
star
26

wdi-shiny

Shiny app to explore World Bank datasets
HTML
7
star
27

isds-webinar

Slides and materials for ISDS R Users Group webinar
HTML
6
star
28

dfw-election-dot-map

Dot map of the 2016 presidential election in Dallas-Fort Worth
R
6
star
29

rmdwebsite

R Markdown source code for my personal website
HTML
6
star
30

whats-new-in-tidycensus

Slides for tidycensus webinar on September 28, 2023
HTML
6
star
31

uw-workshop

Repository for workshop given at UW CSDE in February 2022
R
4
star
32

census-r

Website for "Analyzing US Census Data: Methods, Maps, and Models with R" forthcoming with CRC Press
HTML
4
star
33

urbanslides

Slides for GEOG 10023, "An Urban World", taught Spring 2020 at TCU
HTML
4
star
34

us-boundaries

R
4
star
35

home-value-dots

Dot-density map of owner-occupied home values from the 2018-2022 ACS
HTML
4
star
36

sha2017

Slides and data for Geographic Information Systems workshop at the 2017 Society for Historical Archaeology conference
HTML
3
star
37

gender-age-explorer

Shiny application to explore population structure and gender ratios
HTML
3
star
38

aag2017

Slides and code for presentation at 2017 AAG meetings
R
3
star
39

tigris-article

In-progress article, "Geographic visualization and analysis in R with tigris"
TeX
3
star
40

tigris-webinar

Materials for tigris webinar on April 4, 2017
HTML
3
star
41

tigris-zip-income

Shiny application in support of R Journal submission
R
3
star
42

urbangis

Slides for "GEOG 40323: Urban & Business GIS", taught Spring 2018 at TCU
HTML
2
star
43

qgis-tutorial

Tutorial for geocoding and calculating distances in QGIS
2
star
44

tiles

This repo stores tiles for web mapping.
HTML
2
star
45

oldred

Code and slides for my Sept 19 talk, "Visualizing the changing landscape of US immigration"
HTML
2
star
46

txgis2017

Slides and code for Texas GIS Forum presentation
HTML
1
star
47

dimple-pyramid

Shiny app to create interactive population pyramids - WIP
R
1
star
48

tlc2014

Slides for Teaching and Learning Conversation on March 26, 2014
JavaScript
1
star
49

geog30313

Slides for GEOG 30313: Introduction to GIS at TCU
HTML
1
star
50

map-challenge-2024

Code and maps for 2024's 30 Day Map Challenge
1
star