R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document.

library(tidyverse)
## Warning: package 'tidyverse' was built under R version 4.5.3
## Warning: package 'tidyr' was built under R version 4.5.3
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.6
## ✔ forcats   1.0.1     ✔ stringr   1.6.0
## ✔ ggplot2   4.0.1     ✔ tibble    3.3.0
## ✔ lubridate 1.9.4     ✔ tidyr     1.3.2
## ✔ purrr     1.2.0     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(tmap)
library(sf)
## Linking to GEOS 3.13.1, GDAL 3.11.4, PROJ 9.7.0; sf_use_s2() is TRUE
library(tigris)
## Warning: package 'tigris' was built under R version 4.5.3
## To enable caching of data, set `options(tigris_use_cache = TRUE)`
## in your R script or .Rprofile.
library(tidycensus)
## Warning: package 'tidycensus' was built under R version 4.5.3
library(jsonlite)
## 
## Attaching package: 'jsonlite'
## 
## The following object is masked from 'package:purrr':
## 
##     flatten
library(httr)
library(jsonlite)
library(reshape2)
## 
## Attaching package: 'reshape2'
## 
## The following object is masked from 'package:tidyr':
## 
##     smiths
library(here)
## here() starts at C:/Users/fakaa/Downloads
library(knitr)
library(magrittr)
## Warning: package 'magrittr' was built under R version 4.5.3
## 
## Attaching package: 'magrittr'
## 
## The following object is masked from 'package:purrr':
## 
##     set_names
## 
## The following object is masked from 'package:tidyr':
## 
##     extract

Instructions

COLLECTING POI DATA USING GOOGLE PLACES API

  1. Choose two place types for the “includedTypes” parameter in the Google Places Nearby Search API. Refer to the API documentation for options.

  2. Select a U.S. city. Use the “tigris” package to obtain an “sf” object of the city boundary. Avoid large cities (e.g., Atlanta) to prevent excessive API calls.

  3. Divide the city into small areas using one of the following methods and prepare “locationRestriction” parameter values (longitude, latitude, and radius) for each area: Method 1: Census Block Groups (BGs) that intersect the city polygon Method 2: Fishnet grid cells based on the city polygon

  4. Verify coverage to ensure there are no uncovered areas by visualizing your locationRestriction parameters on a map: Create a POINT “sf” object using longitude, latitude, and sf::st_as_sf(). Create buffers using radius and sf::st_buffer(). Build an interactive map displaying (1) the city boundary and (2) the buffer objects with the tmap package.

  5. Collect POI data using the Nearby Search in the Google Places API. Include two place types in the includedTypes parameter. For FieldMask, include these 8 fields: places.id; places.displayName; places.formattedAddress; places.location; places.types; places.priceLevel; places.rating; places.userRatingCount You may also add other fields of interest, but these 8 must be included. Parse the API response into a data frame. Export the POI dataset into an RData or RDS file.

  6. Map the collected POIs Convert the POI dataset into an sf object using sf::st_as_sf(). Create an interactive map showing both the POIs and the city boundary.

  7. Answer the following questions at the end of your script: What city did you choose? Which two place types did you select? How many rows does your dataset contain? Upon visual inspection, do you notice any spatial patterns in how POIs are distributed across the city? (Optional) Did you observe any other interesting findings?

Working with R Markdown

You may copy and paste the instructions above into your script. Keep your document readable, well-formatted, and concise: Avoid making the document unnecessarily lengthy by printing or plotting everything. Add comments before and/or inside each code chunk (using #) to explain what your code is doing. Remember that every time you click Knit, the entire script runs. Be cautious, as this will directly impact your API usage.

Submission Guidelines Write your report and R code in an R Markdown (.Rmd) script. Use the Knit button in RStudio to render the document as HTML. Publish the rendered HTML to RPubs. Submit the URL of your RPubs document through Canvas by 9/19/2025 Friday 11:59 PM:

Place type. (bank and school)

2. Select a U.S. city. Use the “tigris” package to obtain an sf object of the city boundary.

# Get block groups for DeKalb County (Stone Mountain)
bg <- suppressMessages(
  tidycensus::get_acs(
    geography = "block group",
    state = "GA",
    county = c("DeKalb County"),
    variables = c(hhincome = "B19013_001"),
    year = 2023,
    survey = "acs5",
    geometry = TRUE,
    output = "wide"
  )
)
##   |                                                                              |                                                                      |   0%  |                                                                              |                                                                      |   1%  |                                                                              |=                                                                     |   1%  |                                                                              |=                                                                     |   2%  |                                                                              |==                                                                    |   2%  |                                                                              |==                                                                    |   3%  |                                                                              |==                                                                    |   4%  |                                                                              |===                                                                   |   4%  |                                                                              |===                                                                   |   5%  |                                                                              |====                                                                  |   5%  |                                                                              |====                                                                  |   6%  |                                                                              |=====                                                                 |   7%  |                                                                              |=====                                                                 |   8%  |                                                                              |======                                                                |   8%  |                                                                              |======                                                                |   9%  |                                                                              |=======                                                               |   9%  |                                                                              |=======                                                               |  10%  |                                                                              |=======                                                               |  11%  |                                                                              |========                                                              |  11%  |                                                                              |========                                                              |  12%  |                                                                              |=========                                                             |  13%  |                                                                              |==========                                                            |  14%  |                                                                              |==========                                                            |  15%  |                                                                              |===========                                                           |  15%  |                                                                              |===========                                                           |  16%  |                                                                              |============                                                          |  17%  |                                                                              |============                                                          |  18%  |                                                                              |=============                                                         |  18%  |                                                                              |=============                                                         |  19%  |                                                                              |==============                                                        |  20%  |                                                                              |==============                                                        |  21%  |                                                                              |===============                                                       |  21%  |                                                                              |===============                                                       |  22%  |                                                                              |================                                                      |  22%  |                                                                              |================                                                      |  23%  |                                                                              |=================                                                     |  24%  |                                                                              |=================                                                     |  25%  |                                                                              |==================                                                    |  25%  |                                                                              |==================                                                    |  26%  |                                                                              |===================                                                   |  27%  |                                                                              |====================                                                  |  28%  |                                                                              |====================                                                  |  29%  |                                                                              |=====================                                                 |  29%  |                                                                              |=====================                                                 |  30%  |                                                                              |=====================                                                 |  31%  |                                                                              |======================                                                |  31%  |                                                                              |======================                                                |  32%  |                                                                              |=======================                                               |  33%  |                                                                              |========================                                              |  34%  |                                                                              |========================                                              |  35%  |                                                                              |=========================                                             |  35%  |                                                                              |=========================                                             |  36%  |                                                                              |==========================                                            |  37%  |                                                                              |==========================                                            |  38%  |                                                                              |===========================                                           |  38%  |                                                                              |===========================                                           |  39%  |                                                                              |============================                                          |  40%  |                                                                              |============================                                          |  41%  |                                                                              |=============================                                         |  41%  |                                                                              |=============================                                         |  42%  |                                                                              |==============================                                        |  42%  |                                                                              |==============================                                        |  43%  |                                                                              |===============================                                       |  44%  |                                                                              |===============================                                       |  45%  |                                                                              |================================                                      |  45%  |                                                                              |================================                                      |  46%  |                                                                              |=================================                                     |  47%  |                                                                              |=================================                                     |  48%  |                                                                              |==================================                                    |  48%  |                                                                              |==================================                                    |  49%  |                                                                              |===================================                                   |  49%  |                                                                              |===================================                                   |  50%  |                                                                              |====================================                                  |  51%  |                                                                              |====================================                                  |  52%  |                                                                              |=====================================                                 |  52%  |                                                                              |=====================================                                 |  53%  |                                                                              |======================================                                |  54%  |                                                                              |======================================                                |  55%  |                                                                              |=======================================                               |  55%  |                                                                              |=======================================                               |  56%  |                                                                              |========================================                              |  57%  |                                                                              |========================================                              |  58%  |                                                                              |=========================================                             |  58%  |                                                                              |=========================================                             |  59%  |                                                                              |==========================================                            |  60%  |                                                                              |==========================================                            |  61%  |                                                                              |===========================================                           |  61%  |                                                                              |===========================================                           |  62%  |                                                                              |============================================                          |  62%  |                                                                              |============================================                          |  63%  |                                                                              |=============================================                         |  64%  |                                                                              |=============================================                         |  65%  |                                                                              |==============================================                        |  65%  |                                                                              |==============================================                        |  66%  |                                                                              |===============================================                       |  67%  |                                                                              |===============================================                       |  68%  |                                                                              |================================================                      |  68%  |                                                                              |================================================                      |  69%  |                                                                              |=================================================                     |  69%  |                                                                              |=================================================                     |  70%  |                                                                              |==================================================                    |  71%  |                                                                              |==================================================                    |  72%  |                                                                              |===================================================                   |  72%  |                                                                              |===================================================                   |  73%  |                                                                              |====================================================                  |  74%  |                                                                              |====================================================                  |  75%  |                                                                              |=====================================================                 |  75%  |                                                                              |=====================================================                 |  76%  |                                                                              |======================================================                |  77%  |                                                                              |======================================================                |  78%  |                                                                              |=======================================================               |  78%  |                                                                              |=======================================================               |  79%  |                                                                              |========================================================              |  79%  |                                                                              |========================================================              |  80%  |                                                                              |=========================================================             |  81%  |                                                                              |=========================================================             |  82%  |                                                                              |==========================================================            |  82%  |                                                                              |==========================================================            |  83%  |                                                                              |===========================================================           |  84%  |                                                                              |===========================================================           |  85%  |                                                                              |============================================================          |  85%  |                                                                              |============================================================          |  86%  |                                                                              |=============================================================         |  87%  |                                                                              |==============================================================        |  88%  |                                                                              |==============================================================        |  89%  |                                                                              |===============================================================       |  89%  |                                                                              |===============================================================       |  90%  |                                                                              |===============================================================       |  91%  |                                                                              |================================================================      |  91%  |                                                                              |================================================================      |  92%  |                                                                              |=================================================================     |  92%  |                                                                              |=================================================================     |  93%  |                                                                              |==================================================================    |  94%  |                                                                              |==================================================================    |  95%  |                                                                              |===================================================================   |  95%  |                                                                              |===================================================================   |  96%  |                                                                              |====================================================================  |  97%  |                                                                              |====================================================================  |  98%  |                                                                              |===================================================================== |  98%  |                                                                              |===================================================================== |  99%  |                                                                              |======================================================================|  99%  |                                                                              |======================================================================| 100%
# City of StoneMountain boundary
StoneMountain <- tigris::places("GA") %>%
  filter(NAME == "Stone Mountain")
## Retrieving data for the year 2024
##   |                                                                              |                                                                      |   0%  |                                                                              |=                                                                     |   1%  |                                                                              |=                                                                     |   2%  |                                                                              |==                                                                    |   2%  |                                                                              |==                                                                    |   3%  |                                                                              |===                                                                   |   4%  |                                                                              |===                                                                   |   5%  |                                                                              |====                                                                  |   5%  |                                                                              |====                                                                  |   6%  |                                                                              |=====                                                                 |   6%  |                                                                              |=====                                                                 |   7%  |                                                                              |=====                                                                 |   8%  |                                                                              |======                                                                |   8%  |                                                                              |======                                                                |   9%  |                                                                              |=======                                                               |   9%  |                                                                              |=======                                                               |  10%  |                                                                              |=======                                                               |  11%  |                                                                              |========                                                              |  11%  |                                                                              |========                                                              |  12%  |                                                                              |=========                                                             |  12%  |                                                                              |=========                                                             |  13%  |                                                                              |=========                                                             |  14%  |                                                                              |==========                                                            |  14%  |                                                                              |==========                                                            |  15%  |                                                                              |===========                                                           |  15%  |                                                                              |===========                                                           |  16%  |                                                                              |============                                                          |  17%  |                                                                              |============                                                          |  18%  |                                                                              |=============                                                         |  18%  |                                                                              |=============                                                         |  19%  |                                                                              |==============                                                        |  20%  |                                                                              |==============                                                        |  21%  |                                                                              |===============                                                       |  21%  |                                                                              |===============                                                       |  22%  |                                                                              |================                                                      |  22%  |                                                                              |================                                                      |  23%  |                                                                              |================                                                      |  24%  |                                                                              |=================                                                     |  24%  |                                                                              |=================                                                     |  25%  |                                                                              |==================                                                    |  25%  |                                                                              |==================                                                    |  26%  |                                                                              |===================                                                   |  26%  |                                                                              |===================                                                   |  27%  |                                                                              |===================                                                   |  28%  |                                                                              |====================                                                  |  28%  |                                                                              |====================                                                  |  29%  |                                                                              |=====================                                                 |  29%  |                                                                              |=====================                                                 |  30%  |                                                                              |=====================                                                 |  31%  |                                                                              |======================                                                |  31%  |                                                                              |======================                                                |  32%  |                                                                              |=======================                                               |  32%  |                                                                              |=======================                                               |  33%  |                                                                              |========================                                              |  34%  |                                                                              |========================                                              |  35%  |                                                                              |=========================                                             |  35%  |                                                                              |=========================                                             |  36%  |                                                                              |==========================                                            |  37%  |                                                                              |==========================                                            |  38%  |                                                                              |===========================                                           |  38%  |                                                                              |===========================                                           |  39%  |                                                                              |============================                                          |  40%  |                                                                              |============================                                          |  41%  |                                                                              |=============================                                         |  41%  |                                                                              |=============================                                         |  42%  |                                                                              |==============================                                        |  42%  |                                                                              |==============================                                        |  43%  |                                                                              |===============================                                       |  44%  |                                                                              |===============================                                       |  45%  |                                                                              |================================                                      |  45%  |                                                                              |================================                                      |  46%  |                                                                              |=================================                                     |  47%  |                                                                              |=================================                                     |  48%  |                                                                              |==================================                                    |  48%  |                                                                              |==================================                                    |  49%  |                                                                              |===================================                                   |  49%  |                                                                              |===================================                                   |  50%  |                                                                              |===================================                                   |  51%  |                                                                              |====================================                                  |  51%  |                                                                              |====================================                                  |  52%  |                                                                              |=====================================                                 |  52%  |                                                                              |=====================================                                 |  53%  |                                                                              |=====================================                                 |  54%  |                                                                              |======================================                                |  54%  |                                                                              |======================================                                |  55%  |                                                                              |=======================================                               |  55%  |                                                                              |=======================================                               |  56%  |                                                                              |========================================                              |  56%  |                                                                              |========================================                              |  57%  |                                                                              |========================================                              |  58%  |                                                                              |=========================================                             |  58%  |                                                                              |=========================================                             |  59%  |                                                                              |==========================================                            |  60%  |                                                                              |===========================================                           |  61%  |                                                                              |===========================================                           |  62%  |                                                                              |============================================                          |  62%  |                                                                              |============================================                          |  63%  |                                                                              |=============================================                         |  64%  |                                                                              |=============================================                         |  65%  |                                                                              |==============================================                        |  65%  |                                                                              |==============================================                        |  66%  |                                                                              |===============================================                       |  67%  |                                                                              |===============================================                       |  68%  |                                                                              |================================================                      |  68%  |                                                                              |================================================                      |  69%  |                                                                              |=================================================                     |  69%  |                                                                              |=================================================                     |  70%  |                                                                              |=================================================                     |  71%  |                                                                              |==================================================                    |  71%  |                                                                              |==================================================                    |  72%  |                                                                              |===================================================                   |  72%  |                                                                              |===================================================                   |  73%  |                                                                              |====================================================                  |  74%  |                                                                              |====================================================                  |  75%  |                                                                              |=====================================================                 |  75%  |                                                                              |=====================================================                 |  76%  |                                                                              |======================================================                |  77%  |                                                                              |======================================================                |  78%  |                                                                              |=======================================================               |  78%  |                                                                              |=======================================================               |  79%  |                                                                              |========================================================              |  80%  |                                                                              |========================================================              |  81%  |                                                                              |=========================================================             |  81%  |                                                                              |=========================================================             |  82%  |                                                                              |==========================================================            |  82%  |                                                                              |==========================================================            |  83%  |                                                                              |===========================================================           |  84%  |                                                                              |===========================================================           |  85%  |                                                                              |============================================================          |  85%  |                                                                              |============================================================          |  86%  |                                                                              |=============================================================         |  87%  |                                                                              |=============================================================         |  88%  |                                                                              |==============================================================        |  88%  |                                                                              |==============================================================        |  89%  |                                                                              |===============================================================       |  90%  |                                                                              |===============================================================       |  91%  |                                                                              |================================================================      |  91%  |                                                                              |================================================================      |  92%  |                                                                              |=================================================================     |  92%  |                                                                              |=================================================================     |  93%  |                                                                              |=================================================================     |  94%  |                                                                              |==================================================================    |  94%  |                                                                              |==================================================================    |  95%  |                                                                              |===================================================================   |  95%  |                                                                              |===================================================================   |  96%  |                                                                              |====================================================================  |  97%  |                                                                              |====================================================================  |  98%  |                                                                              |===================================================================== |  98%  |                                                                              |===================================================================== |  99%  |                                                                              |======================================================================|  99%  |                                                                              |======================================================================| 100%
# Get BGs intersecting with the City of StoneMountain boundary
bg_StoneMountain <- bg[StoneMountain, ]

3. Divide the city into small areas using one of the following methods and prepare “locationRestriction” parameter values (longitude, latitude, and radius) for each area:

Method 1: Census Block Groups (BGs) that intersect the city polygon Method 2: Fishnet grid cells based on the city polygon Verify coverage to ensure there are no uncovered areas by visualizing your locationRestriction parameters on a map:

Method 1: Using the Census Block Groups (BGs) that intersect the city polygon

# Function: Get XY coordinates and radius
getXYRadius <- function(polygon, gcs_id, pcs_id) {
  # Transform the CRS to PCS.
  if (st_crs(polygon) != st_crs(pcs_id)) {
    polygon <- polygon %>% st_transform(pcs_id)
  }
  # Get bounding box of a given polygon
  bb <- st_bbox(polygon)
  # Get XY coordinates of any one corner of the bounding box.
  bb_corner <- st_point(c(bb[1], bb[2])) %>%
    st_sfc(crs = pcs_id)
  # Get centroid of the bb
  bb_center <- bb %>%
    st_as_sfc() %>%
    st_centroid()
  # Get the distance between bb_center and bb_corner
  r <- st_distance(bb_corner, bb_center)
  # Convert the CRS of centroid to GCS.
  bb_center <- bb_center %>% st_transform(gcs_id)
  # Get longitude and latitude
  xy <- bb_center %>% st_coordinates() %>% as.vector()
  lon_lat_radius <- data.frame(x = xy[1], 
                               y = xy[2], 
                               r = r)
  return(lon_lat_radius)
}

We can apply this function to each BG.

# Define EPSG codes for GCS (WGS 84) and PCS (WGS 84 / UTM zone 16N)
gcs_id <- 4326
pcs_id <- 32616

# Pre-allocate a data frame for StoneMountain BGs
bg_StoneMountain_xyr <- data.frame(
  x = numeric(nrow(bg_StoneMountain)),
  y = NA,
  r = NA
)


# For-loop over BGs in StoneMountain
for (i in 1:nrow(bg_StoneMountain)) {
  bg_StoneMountain_xyr[i, ] <- bg_StoneMountain[i, ] %>%
    getXYRadius(gcs_id = gcs_id, pcs_id = pcs_id)
}

Visualization of the Census Block Groups (BGs)

tmap_mode("view")
## ℹ tmap modes "plot" - "view"
## ℹ toggle with `tmap::ttm()`
bg_StoneMountain_xyr %>%
  st_as_sf(coords = c("x", "y"), crs = st_crs(bg_StoneMountain)) %>%
  st_buffer(dist = .$r) %>%
  tm_shape() +
  tm_polygons(alpha = 0.3, col = "red") +
  tm_shape(bg_StoneMountain) +
  tm_borders(col = "blue")
## 
## ── tmap v3 code detected ───────────────────────────────────────────────────────
## [v3->v4] `tm_polygons()`: use 'fill' for the fill color of polygons/symbols
## (instead of 'col'), and 'col' for the outlines (instead of 'border.col').[v3->v4] `tm_polygons()`: use `fill_alpha` instead of `alpha`.

Method 2: Fishnet grid cells based on the city polygon and Visualization

# Get bbox for StoneMountain
StoneMountain_bb <- StoneMountain %>%
  st_transform(pcs_id) %>%
  st_bbox()

# Coordinates for bbox sides
west  <- StoneMountain_bb[1]
east  <- StoneMountain_bb[3]
south <- StoneMountain_bb[2]
north <- StoneMountain_bb[4]

# Split bbox into a grid
fishnet_n <- 4
dist <- abs(east - west) / fishnet_n

# Fishnet points
fish_x <- seq(from = west, to = east, by = dist)
fish_y <- seq(from = south, to = north, by = dist)

fishnet <- expand.grid(fish_x, fish_y) %>%
  rename(x = Var1, y = Var2) %>%
  st_as_sf(coords = c("x", "y"), crs = pcs_id)

fishnet$x <- fishnet %>%
  st_transform(gcs_id) %>%
  st_coordinates() %>%
  .[, 1]

fishnet$y <- fishnet %>%
  st_transform(gcs_id) %>%
  st_coordinates() %>%
  .[, 2]

fishnet$r <- dist * (2^(1/2) / 2)

# Visualize fishnet over StoneMountain

fishnet %>%
  st_buffer(dist = .$r) %>%
  tm_shape() +
  tm_polygons(alpha = 0.1, col = "red") +
  tm_shape(StoneMountain) +
  tm_borders(lwd = 3)
## 
## ── tmap v3 code detected ───────────────────────────────────────────────────────
## [v3->v4] `tm_polygons()`: use `fill_alpha` instead of `alpha`.

Collect POI data using the Nearby Search in the Google Places API.

Parse the API response into a data frame.

First STEP ( This step will help to make a Nearby Search request using POST (an HTTP method) and parse the response.)

library(httr)

google_api_key <- Sys.getenv("GOOGLE_API")

# Approximate center of Stone Mountain, GA (DeKalb County, Atlanta metro)
lat <- 33.8053   # Stone Mountain area
lon <- -84.1703
radius <- 500.0

endpoint <- "https://places.googleapis.com/v1/places:searchNearby"

body <- list(
  includedTypes = list("bank", "school"),
  locationRestriction = list(
    circle = list(
      center = list(latitude = lat, longitude = lon),
      radius = radius
    )
  )
)

resp <- httr::POST(
  endpoint,
  httr::add_headers(
    "Content-Type"      = "application/json",
    "X-Goog-Api-Key"    = google_api_key,
    "X-Goog-FieldMask"  = "places.displayName,places.formattedAddress,places.types"
  ),
  body = body,
  encode = "json"
)

data <- httr::content(resp, as = "text") %>%
  jsonlite::fromJSON(flatten = TRUE) %>%
  as.data.frame()

print(data)
##                                                                                                      places.types
## 1                            school, government_office, point_of_interest, educational_institution, establishment
## 2                     bank, atm, insurance_agency, consultant, finance, service, point_of_interest, establishment
## 3 school, association_or_organization, health, service, point_of_interest, educational_institution, establishment
## 4                                      school, service, point_of_interest, educational_institution, establishment
## 5                                               school, point_of_interest, educational_institution, establishment
##                             places.formattedAddress
## 1     5265 Mimosa Dr, Stone Mountain, GA 30083, USA
## 2 5399 E Mountain St, Stone Mountain, GA 30083, USA
## 3        927 Main St, Stone Mountain, GA 30083, USA
## 4 5283 W Mountain St, Stone Mountain, GA 30083, USA
## 5 5312 W Mountain St, Stone Mountain, GA 30083, USA
##         places.displayName.text places.displayName.languageCode
## 1        Champion Middle School                              en
## 2                        Truist                              en
## 3 Kameo Production Studios, LLC                              en
## 4              Vastshades Music                              en
## 5     Valor Preparatory Academy                              en

Second STEP (the outcome of the POST call is required to be printed. This will show the API response object. We will use the print fuction for ‘resp’)

data <- content(resp, as = "text")

data <- jsonlite::fromJSON(data, flatten = TRUE) %>%
  as.data.frame()

Third STEP (Extracting the data content into a data frame and parsing it would help in its usage)

print(resp) # metadata + body
## Response [https://places.googleapis.com/v1/places:searchNearby]
##   Date: 2026-10-02 21:53
##   Status: 200
##   Content-Type: application/json; charset=UTF-8
##   Size: 1.82 kB
## {
##   "places": [
##     {
##       "types": [
##         "school",
##         "government_office",
##         "point_of_interest",
##         "educational_institution",
##         "establishment"
##       ],
## ...

Fourth STEP (We need to be sure that data we are parse is accurate and that the output is accurately shown in the location that we are interested)

print(data)
##                                                                                                      places.types
## 1                            school, government_office, point_of_interest, educational_institution, establishment
## 2                     bank, atm, insurance_agency, consultant, finance, service, point_of_interest, establishment
## 3 school, association_or_organization, health, service, point_of_interest, educational_institution, establishment
## 4                                      school, service, point_of_interest, educational_institution, establishment
## 5                                               school, point_of_interest, educational_institution, establishment
##                             places.formattedAddress
## 1     5265 Mimosa Dr, Stone Mountain, GA 30083, USA
## 2 5399 E Mountain St, Stone Mountain, GA 30083, USA
## 3        927 Main St, Stone Mountain, GA 30083, USA
## 4 5283 W Mountain St, Stone Mountain, GA 30083, USA
## 5 5312 W Mountain St, Stone Mountain, GA 30083, USA
##         places.displayName.text places.displayName.languageCode
## 1        Champion Middle School                              en
## 2                        Truist                              en
## 3 Kameo Production Studios, LLC                              en
## 4              Vastshades Music                              en
## 5     Valor Preparatory Academy                              en

The confirmation of the a successiful API dynogsis means that we can now process the response. the place type and field mask are converted into lists and comma-separated string for compliance.

nearbySearch <- function(lat, lon, radius, types_vec, fieldmask_vec, google_api_key) {
  endpoint <- "https://places.googleapis.com/v1/places:searchNearby"
  
  body <- list(
    includedTypes = as.list(types_vec),
    locationRestriction = list(
      circle = list(
        center = list(latitude = lat, longitude = lon),
        radius = radius
      )
    ),
    rankPreference = "DISTANCE"
  )
  
  resp <- httr::POST(
    endpoint,
    httr::add_headers(
      "Content-Type"     = "application/json",
      "X-Goog-Api-Key"   = google_api_key,
      "X-Goog-FieldMask" = paste(fieldmask_vec, collapse = ",")
    ),
    body = body,
    encode = "json"
  )
  
  data <- httr::content(resp, as = "text") %>%
    jsonlite::fromJSON(flatten = TRUE) %>%
    as.data.frame()
  
  if (nrow(data) == 20) {
    print("WARNING: The response has 20 rows! Consider using a smaller spatial unit.")
  }
  
  return(data)
}

Similarly, we can be specific in sending a request using the Nearby Search API function that will return the same result as previously.

nearbySearch(
  lat = 33.8053,
  lon = -84.1703,
  radius = radius,
  types_vec = c("bank", "school"),
  fieldmask_vec = c(
    "places.id",
    "places.displayName",
    "places.formattedAddress",
    "places.location",
    "places.types",
    "places.priceLevel",
    "places.rating",
    "places.userRatingCount"
  ),
  google_api_key = Sys.getenv("GOOGLE_API")
)
##                     places.id
## 1 ChIJh_QLfzuv9YgRGWYoRfULfnw
## 2 ChIJwZxCxjqv9YgRSnZHAanPp_s
## 3 ChIJD2Xmajyv9YgRY0lWo8JoyQo
## 4 ChIJUZHfEgGv9YgRARArrwpbQB4
## 5 ChIJJQQ1JsKv9YgRnQjfaoFseAs
##                                                                                                      places.types
## 1 school, association_or_organization, health, service, point_of_interest, educational_institution, establishment
## 2                            school, government_office, point_of_interest, educational_institution, establishment
## 3                     bank, atm, insurance_agency, consultant, finance, service, point_of_interest, establishment
## 4                                      school, service, point_of_interest, educational_institution, establishment
## 5                                               school, point_of_interest, educational_institution, establishment
##                             places.formattedAddress places.rating
## 1        927 Main St, Stone Mountain, GA 30083, USA            NA
## 2     5265 Mimosa Dr, Stone Mountain, GA 30083, USA            NA
## 3 5399 E Mountain St, Stone Mountain, GA 30083, USA           3.6
## 4 5283 W Mountain St, Stone Mountain, GA 30083, USA           5.0
## 5 5312 W Mountain St, Stone Mountain, GA 30083, USA            NA
##   places.userRatingCount places.location.latitude places.location.longitude
## 1                     NA                 33.80676                 -84.17016
## 2                     NA                 33.80519                 -84.17398
## 3                     40                 33.80817                 -84.16881
## 4                      4                 33.80756                 -84.17331
## 5                     NA                 33.80863                 -84.17199
##         places.displayName.text places.displayName.languageCode
## 1 Kameo Production Studios, LLC                              en
## 2        Champion Middle School                              en
## 3                        Truist                              en
## 4              Vastshades Music                              en
## 5     Valor Preparatory Academy                              en

Applying the function to all Census BGs

Now that we have the Nearby Search API function, we can repeat this process for all the Census BGs using the bg_StoneMountain_xyr object we created earlier.

# Pre-allocate list
data_list <- vector("list", nrow(bg_StoneMountain_xyr))

for (i in seq_len(nrow(bg_StoneMountain_xyr))) {
  data_list[[i]] <- nearbySearch(
    lat = bg_StoneMountain_xyr$y[i],
    lon = bg_StoneMountain_xyr$x[i],
    radius = bg_StoneMountain_xyr$r[i],
    types_vec = c("bank", "school"),
    fieldmask_vec = c(
      "places.id",
      "places.displayName",
      "places.formattedAddress",
      "places.location",
      "places.types",
      "places.priceLevel",
      "places.rating",
      "places.userRatingCount"
    ),
    google_api_key = Sys.getenv("GOOGLE_API")
  )
  Sys.sleep(1)
}
## [1] "WARNING: The response has 20 rows! Consider using a smaller spatial unit."
# Combine all data frames
data_all <- dplyr::bind_rows(data_list)

Saving the data in a RDS file would mean that we can always use it going forward with wasting our API google subscription on the same data if we need to use it in future.

saveRDS(data_all, here("mini_assignment_1_T_otoo_NEW.rds"))

Visualisation of google places data on banks and schools in Stone Mountain

# Convert the data to an sf object using XY coordinates

data_all_sf <- data_all %>%
  dplyr::rename(
    x = places.location.longitude,
    y = places.location.latitude
  ) %>%
  dplyr::filter(!is.na(x) & !is.na(y)) %>%
  sf::st_as_sf(coords = c("x", "y"), crs = 4326)


# Map POIs and Stone Mountain boundary
tmap_mode("view")
## ℹ tmap modes "plot" - "view"
tm_shape(data_all_sf) +
  tm_dots(
    col = "places.rating",
    size = "places.userRatingCount",
    palette = "magma",
    popup.vars = c(
      "Name"         = "places.displayName.text",
      "Rating"       = "places.rating",
      "Rating Count" = "places.userRatingCount"
    )
  ) +
  tm_shape(StoneMountain) +
  tm_borders()
## 
## ── tmap v3 code detected ───────────────────────────────────────────────────────
## [v3->v4] `tm_tm_dots()`: migrate the argument(s) related to the scale of the
## visual variable `fill` namely 'palette' (rename to 'values') to fill.scale =
## tm_scale(<HERE>).

QUESTIONS AND ANSWERS TO INSTRUCTION SEVEN (7)

  1. What city did you choose?

Answer: I chose a city called Stone Mountain. It is located in DeKalb County in the State of Georgia, USA.

  1. Which two place types did you select?

Answer: The place types selected were banks and schools

  1. How many rows does your dataset contain?

Answer: the dataset contains one row

  1. Upon visual inspection, do you notice any spatial patterns in how POIs are distributed across the city?

Answer: There are medium ratings in terms of place ratings and high ratings on place user rating counts in the northern part of the city compared to the southern part. Again, the central part of the city does not show any form of rating in the city, using banks and schools as a reference point. The distribution of the POIs in the city could be highly affected when there are missing values to report from the Nearby search.

  1. (Optional) Did you observe any other interesting findings?

Answer: Nearby search also showed place ratings and place user ratings of a location that is well beyond the boundary of the study location (Stone Mountain).