## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  eval = nzchar(Sys.getenv("CLOSECITY_KEY"))
)
library(closecity)
library(sf)
close <- closecity::close_client(api_key = Sys.getenv("CLOSECITY_KEY"))

## -----------------------------------------------------------------------------
# amenity_types <- close$destination_types()
# ids <- setNames(amenity_types$dest_type_id, amenity_types$label)
# cafe <- ids[["cafes"]]
# 
# city <- close$places(q = "Providence")[1, ]
# city_boundary <- close$place_boundary(geoid = city$geoid)

## -----------------------------------------------------------------------------
# cafes <- close$place_pois(geoid = city$geoid, type = cafe)
# ours <- cafes[1, ]
# ours$name
# 
# our_shed <- close$poi_catchment(dest_id = ours$dest_id, mode = "walk",
#                                 max_minutes = 10)
# closecity::close_map(
#   x = cafes,
#   color = ifelse(cafes$dest_id == ours$dest_id, "#f36e21", "#202a5b"),
#   label = "name",
#   background = sf::st_union(our_shed),
#   background_color = "#74b9ff",
#   boundary = city_boundary
# )

## -----------------------------------------------------------------------------
# reach <- close$block_pois(
#   our_shed$geoid,
#   mode = "walk", type = cafe, max_minutes = 10, output = "tabular"
# )
# 
# per_block <- split(reach, reach$geoid)
# counts <- vapply(per_block, nrow, integer(1))
# closest <- vapply(
#   per_block, function(r) r$dest_id[which.min(r$travel_time)], numeric(1)
# )
# our_shed$n_cafes <- unname(counts[as.character(our_shed$geoid)])
# our_shed$n_cafes[is.na(our_shed$n_cafes)] <- 0L
# our_shed$closest_cafe <- unname(closest[as.character(our_shed$geoid)])

## -----------------------------------------------------------------------------
# reachable <- cafes[cafes$dest_id %in% unique(reach$dest_id), ]
# closecity::close_map(
#   x = our_shed,
#   fill = "n_cafes",
#   reverse = TRUE,
#   points = reachable,
#   boundary = city_boundary
# )

## -----------------------------------------------------------------------------
# closest <- unique(stats::na.omit(our_shed$closest_cafe))
# palette <- setNames(grDevices::hcl.colors(length(closest), "Dark 3"), closest)
# 
# block_color <- palette[as.character(our_shed$closest_cafe)]
# block_color[is.na(block_color)] <- "#dddddd"
# 
# winning_cafes <- cafes[cafes$dest_id %in% closest, ]
# closecity::close_map(
#   x = our_shed,
#   color = block_color,
#   points = winning_cafes,
#   points_color = palette[as.character(winning_cafes$dest_id)],
#   boundary = city_boundary
# )

