Dr_Watcher
Dr_Watcher

Reputation: 67

How to iterate through url in R?

I'm trying to iterate through a url with different coordinates. The url I want to iterate through is the Google Api textsearch.

This is an example of a textsearch url and its parameters. I need to iterate in the location parameter.

https://maps.googleapis.com/maps/api/place/textsearch/json?query=123+main+street&location=42.3675294,-71.186966&radius=10000&key=YOUR_API_KEY

I have a dataframe with columns for latitude and longitude. Suppose its called Cords.

Using the language R, I want to do something like this:

for i in 1:length(Cords$lat){
    lat = Cords$lat[i]
    lon = Cords$lon[i] 
    https://maps.googleapis.com/maps/api/place/textsearch/json?query=123+main+street&location=lat,lon&radius=10000&key=YOUR_API_KEY
}

I store each iteration in another dataframe, I didn't include that code.

Upvotes: 0

Views: 518

Answers (3)

SymbolixAU
SymbolixAU

Reputation: 26258

As @hrbrmstr alludes/links to you can use my googleway package, which wraps the Google Places API (and various others) for you

library(googleway)

df <- data.frame(lat=c(42.3675294, 43.6615, 43.2081),
                 lon=c(-71.186966, -70.2553, 71.5376))

## your api key goes here
##api_key <- xxxx

## single query
google_places(search_string = "123 Main St", 
              location = c(df[1,"lat"], df[1,"lon"]),
              key = api_key)


## multiple queries
lst <- apply(df, 1, function(x){
    google_places(search_string = "123 Main St", 
                  location = c(x["lat"], x["lon"]),
                  key = api_key)
})

lst is now a list of all the results, so for example we can look at all the addresses

lapply(lst, function(x){ x[["results"]][["formatted_address"]] })
# [[1]]
# [1] "123 Main St, Watertown, MA 02472, USA"
# 
# [[2]]
# [1] "123 Main St, South Portland, ME 04106, USA" "123 Main St, Westbrook, ME 04092, USA"     
# 
# [[3]]
# [1] "123 Main St, Watertown, MA 02472, United States

Upvotes: 0

hrbrmstr
hrbrmstr

Reputation: 78832

This is just begging for a function wrapper. Also, this answer uses sprintf() vs paste() and treats the API like an actual API vs a pasted URL string and tries to help avoid having bare API keys in scripts:

library(httr)
library(jsonlite)
library(purrr)

find_places <- function(query, lon, lat, radius, api_key=Sys.getenv("GOOGLE_API_KEY")) {

  res <- GET("https://maps.googleapis.com/maps/api/place/textsearch/json",
             query=list(query=query,
                        location=sprintf("%s,%s", lat, lon),
                        radius=radius,
                        key=api_key))

  fromJSON(content(res, as="text"), flatten=TRUE)

}

df <- data.frame(lat=c(42.3675294, 43.6615, 43.2081),
                 lon=c(-71.186966, -70.2553, 71.5376))

map2(df$lon, df$lat, ~find_places("123 Main St", .x, .y, 10000)) %>% 
  map_df(out, "results") -> places

dplyr::glimpse(places)
## Observations: 11
## Variables: 18
## $ formatted_address               <chr> "123 Main St, Watertown, MA 02472, USA"...
## $ icon                            <chr> "https://maps.gstatic.com/mapfiles/plac...
## $ id                              <chr> "b2ac1cc162773261571dd4b939b2e6c7ce4cb0...
## $ name                            <chr> "123 Main St", "123 Main St", "123 Main...
## $ place_id                        <chr> "ChIJ3aqMmgZ444kRgD5YevF7_tc", "EioxMjM...
## $ reference                       <chr> "CmRbAAAAo1HUpDIAKtCjc1DCe366g0ehMA_Od5...
## $ types                           <list> ["street_address", "street_address", "...
## $ geometry.location.lat           <dbl> 42.36753, 43.63520, 43.67802, 42.36753,...
## $ geometry.location.lng           <dbl> -71.18697, -70.28722, -70.33530, -71.18...
## $ geometry.viewport.northeast.lat <dbl> 42.36771, 43.63521, 43.67804, NA, 41.98...
## $ geometry.viewport.northeast.lng <dbl> -71.18689, -70.28721, -70.33529, NA, -8...
## $ geometry.viewport.southwest.lat <dbl> 42.36698, 43.63519, 43.67801, NA, 41.98...
## $ geometry.viewport.southwest.lng <dbl> -71.18720, -70.28724, -70.33530, NA, -8...
## $ photos                          <list> [NULL, NULL, NULL, <2112, <a href="htt...
## $ rating                          <dbl> NA, NA, NA, 4.7, 4.6, 4.5, 4.2, NA, 4.5...
## $ price_level                     <int> NA, NA, NA, NA, NA, 2, NA, NA, NA, NA, NA
## $ opening_hours.open_now          <lgl> NA, NA, NA, FALSE, FALSE, FALSE, NA, NA...
## $ opening_hours.weekday_text      <list> [NULL, NULL, NULL, [], [], [], NULL, N...

You may also be able to use the package mentioned in this answer.

Upvotes: 2

Jaime Caffarel
Jaime Caffarel

Reputation: 2469

You can use the paste function to build your URLs.

Coords <- data.frame(lat = c(1.234, 2.456, 3.456), lon = c(5.678, 6.789, 7.890))

for (i in 1:length(Coords$lat)){
  lat = Coords$lat[i]
  lon = Coords$lon[i] 
  url <- paste('https://maps.googleapis.com/maps/api/place/textsearch/json?query=123+main+street&location=',
lat, ',', lon, '&radius=10000&key=YOUR_API_KEY', sep = "")
  print(url)
}

[1] "https://maps.googleapis.com/maps/api/place/textsearch/json?query=123+main+street&location=1.234,5.678&radius=10000&key=YOUR_API_KEY"
[1] "https://maps.googleapis.com/maps/api/place/textsearch/json?query=123+main+street&location=2.456,6.789&radius=10000&key=YOUR_API_KEY"
[1] "https://maps.googleapis.com/maps/api/place/textsearch/json?query=123+main+street&location=3.456,7.89&radius=10000&key=YOUR_API_KEY"

Upvotes: 0

Related Questions