R/query_alt_fuel_api.R

Defines functions nearest_fuel get_coords dist_to_e85

Documented in dist_to_e85 get_coords nearest_fuel

#' Query NREL Alt Fuel Locator
#' Use the NREL apt fuel API to look up the nearest station to a given zipcode with E85 fuel.
#' @param zipcode Character. The zipcode to use as a starting point.
#' @param fuel_type Character. Which fuel code to search for in the API.
#' @param api_key Character. A valid NRAL API key.
#' @param lookup Logical. Should the zipcode be converted to lat/lng before search?
#' @param range Character or numeric. The range in which to conduct the search.
#'
#' @return A list.
#' @export
#'
#' @examples
#' # nearest_85("20001")
nearest_fuel <- function(zip_code, fuel_type = "all",
                         api_key = NA, lookup = TRUE,
                         range = "infinite") {
    require(httr)
    require(jsonlite)

    if (is.na(api_key)) api_key = Sys.getenv("NREL_API")

    api_url = "https://developer.nrel.gov/api/alt-fuel-stations/v1/nearest.json"

    api_key = paste("api_key", api_key, sep = "=")
    location = paste("location", zip_code, sep = "=")
    fuel_type = paste("fuel_type" , fuel_type, sep = "=")
    range = paste("range", range, sep = "=")

    if (lookup) {
        loc <- get_coords(zip_code)
        lat = paste("latitude", loc$latitude, sep = "=")
        lng = paste("longitude", loc$longitude, sep = "=")
        request = paste(api_key, fuel_type, range, lat, lng, sep = "&")
    } else {
        request = paste(api_key, location, fuel_type, range, sep = "&")
    }

    q_url = paste(api_url, request, sep = "?")

    response <- GET(q_url)
    if (response$status_code == 200) {
        return(fromJSON(rawToChar(response$content)))
    } else {
        return(response$status_code)
    }
}

#' Lookup Zipcode Coordinates
#'
#' @param zip character.
#'
#' @return a data frame with city, state, and lat/lng
get_coords <- function(zip_code) {
    require(zipcode)
    data(zipcode, envir = environment())
    return(zipcode[zipcode$zip == zip_code, ])
}

#' Find nearest station with E85 fuel.
#'
#' @param zip_code A character. The zipcode to use as a point of reference.
#' @param units A character. One of "miles" or "km". Defaults to miles.
#' @param ...
#'
#' @return Numeric. The distance to the nearest E85 station in specified units.
#' @export
#'
#' @examples
#' # dist_to_E85("20001", untis = "miles")
dist_to_e85 <- function(zip_code, units = "miles", ...) {
    x <- nearest_fuel(zip_code, fuel_type = "E85", ...)
    if (units == "miles") {
        d <- x$fuel_stations$distance
    } else if (units == "km") {
        d <- x$fuel_stations$distance_km
    } else {
        stop("Units not recognized. Must be `miles` or `km`.")
    }
    if(is.null(d)) d <- c(500)
    return(d[1])
}
burch-cm/fleetreportr documentation built on Nov. 4, 2019, 8:20 a.m.