library(rjson)
library(RCurl)

#### geocoding of towing addresses  #####

# https's for Google Maps Geocoding API
addresses <- DOT_Towing$towedFromLocation %>% as.character()

API_requests <- list()
for (i in 1:length(addresses)) {
  addresses[i] <- str_c(addresses[i], ", Baltimore, MD") 
  addresses[i] <- gsub(pattern = " ", 
                       replacement = "+", 
                       x = addresses[i])
  API_requests[i] <- str_c("https://maps.googleapis.com/maps/api/geocode/json?address=", 
                           addresses[i], "&key=", API_KEY)
}

# function to submit API requests
get_coords <- function (filename, start_address, end_address) {

  # Google Maps Geocoding API requests
  # Inputs:
  #    filename: string
  #    start_address: int (ordinal number to begin requests)
  #    end_address: int (ordinal number to end request)
  #
  # Output:
  #    written R object (list) of API requests

  raw_coords = list()
  j <- 1
  for (i in start_address:end_address) {
    raw_coords[j] <- getURL(API_requests[i]) %>% fromJSON()
    Sys.sleep(0.13)  # to not exceed API rate limit
    j <- j + 1
  }
  raw_coords %>% dput(file = filename)
}

get_coords("API_coords_1-10K.Rlist", 1, 10000)
get_coords("API_coords_10K-20K.Rlist", 10001, 20000)
get_coords("API_coords_20K-30K.Rlist", 20001, 30000)
get_coords("API_coords_30K-40K.Rlist", 30001, 40000)
get_coords("API_coords_40K-50K.Rlist", 40001, 50000)
get_coords("API_coords_50K-end.Rlist", 50001, length(addresses))

#### create summary dataframe geocoded addresses  #####

raw_API_10K <- dget("API_coords_1-10K.Rlist")
raw_API_20K <- dget("API_coords_10K-20K.Rlist")
raw_API_30K <- dget("API_coords_20K-30K.Rlist")
raw_API_40K <- dget("API_coords_30K-40K.Rlist")
raw_API_50K <- dget("API_coords_40K-50K.Rlist")
raw_API_60K <- dget("API_coords_50K-end.Rlist")

raw_API_total <- c(raw_API_10K, 
                   raw_API_20K, 
                   raw_API_30K, 
                   raw_API_40K, 
                   raw_API_50K, 
                   raw_API_60K)

postal_address <- character()
lat <- double()
lng <- double()

for (i in 1:length(raw_API_total)) {
  try(postal_address[i] <- raw_API_total[[i]][[1]]$formatted_address, silent = TRUE)
  try(lat[i] <- raw_API_total[[i]][[1]]$geometry$location$lat, silent = TRUE)
  try(lng[i] <- raw_API_total[[i]][[1]]$geometry$location$lng, silent = TRUE)
}

data.frame("Postal Address" = postal_address, "Lat" = lat, "Lng" = lng) %>%
  write.csv(file = "geocoded_addresses.csv", row.names = FALSE)