如何在R中遍历url?

时间:2016-12-04 07:55:44

标签: r google-maps search google-api logic

我正在尝试使用不同坐标遍历网址。我要迭代的网址是Google Api textsearch。

这是textsearch网址及其参数的示例。我需要迭代位置参数。

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

我有一个包含纬度和经度列的数据框。假设它叫做Cords。

使用语言R,我想做这样的事情:

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
}

我将每个迭代存储在另一个数据帧中,我没有包含该代码。

2 个答案:

答案 0 :(得分:0)

您可以使用paste功能构建您的网址。

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"

答案 1 :(得分:0)

由于@hrbrmstr暗示/链接到您,您可以使用我的googleway包,其中包含Google Places API(以及其他各种用户)

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现在是所有结果的列表,例如我们可以查看所有地址

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
相关问题