Created
March 9, 2022 20:12
-
-
Save mrecos/eac7c989ae4ff1c8ab4c1ea802f45a8c to your computer and use it in GitHub Desktop.
Example of using the Google API and {googleway} package to create time and distance matrices
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# google distance example | |
library(tidyverse) | |
library(googleway) | |
api_key <- "GET A GOOGLE API KEY" | |
## set up a data.frame of locations | |
## can also use 'lat/lon' coordinates as the origin/destination | |
df_locations <- data.frame( | |
origin = c("Melbourne, Australia", "Sydney, Australia","Canberra, Australia") | |
, destination = c("Sydney, Australia", "Brisbane, Australia","Wollongong, Australia") | |
, stringsAsFactors = F | |
) | |
## loop over each pair of locations, and extract the polyline from the result | |
lst_distances <- apply(df_locations, 1, function(x){ | |
res <- google_distance( | |
key = api_key, | |
origin = x[['origin']], | |
destination = x[['destination']]) | |
distance_m <- res$rows$elements[[1]]$distance$value | |
duration_sec <- res$rows$elements[[1]]$duration$value | |
df_result <- data.frame( | |
origin = x[['origin']], | |
destination = x[['destination']], | |
distance_m = distance_m, | |
duration_sec = duration_sec) | |
# rownames(df_result) <- NULL | |
return(df_result) | |
}) | |
## convert the results to a data.frame | |
df_distances <- do.call(rbind, lst_distances) | |
## pivot to pairwise matrix of time | |
duration_matrix <- df_distances %>% | |
select(-distance_m) %>% | |
pivot_wider(names_from = destination, | |
values_from = duration_sec) | |
## pivot to pairwise matrix of distance | |
distance_matrix <- df_distances %>% | |
select(-duration_sec) %>% | |
pivot_wider(names_from = destination, | |
values_from = distance_m) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment