#' Calculate travel time from ANY coordinate system
#'
#' Calculate travel time from coordinates via Google Maps API.
#' Can use any coordinate system. The default is "+proj=longlat +datum=WGS84"
#' which is the one Google Maps prefers. Requires a Google Maps dev key.
#'
#' @param x_start numeric vector of coordinates in any coordinate format
#' @param y_start numeric vector of coordinates in any coordinate format
#' @param x_end numeric vector of coordinates in any coordinate format
#' @param y_end numeric vector of coordinates in any coordinate format
#' @param mode mode in gmapdistance package, e.g. "driving".
#' @param crs the coordinate system (e.g. "+proj=utm +zone=32N +datum=WGS84")
#' @param key Google API key
#' @return data frame with travel time and distance
#' @examples
#' traveltime(x_start = 10.73426, y_start = 59.95023,
#' x_end = 10.74455, y_end = 59.95137,
#' mode = "driving", key = my_key)
traveltime <- function(x_start, x_end, y_start, y_end, crs = NULL, mode, key, silent = TRUE){
library(gmapsdistance)
library(dplyr)
if(!is.null(crs)){
start <- reproj(x_start, y_start, crs = crs) %>%
select(-id)
end <- reproj(x_end, y_end, crs = crs)
} else {
start <- data.frame(x = x_start, y = y_start)
end <- data.frame(x = x_end, y = y_end)
}
st <- start %>%
mutate(xy=paste0(y,"+",x))
sl <- end %>%
mutate(xy=paste0(y,"+",x))
dist <- list()
for(i in 1:nrow(start)){
if(!silent){
print(paste("start-end point", i))
}
dist[[length(dist) + 1]] <- gmapsdistance(origin = st$xy[i], destination = sl$xy[i],
mode = mode, key = key)
}
time <- lapply(dist, `[[`, 1) %>% unlist()
distance <- lapply(dist, `[[`, 2) %>% unlist()
status <- lapply(dist, `[[`, 3) %>% unlist()
start <- start %>%
rename(start_x = x, start_y = y)
end <- end %>%
rename(end_x = x, end_y = y)
df <- data.frame(start, end, time, distance, status)
return(df)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.