【问题标题】:R Geocode with google with search restrictions to a countryR地理编码与谷歌与一个国家的搜索限制
【发布时间】:2020-02-11 07:17:43
【问题描述】:

我试图过滤掉来自某个国家/地区的搜索结果,因为 API 有时会返回随机纬度和经度。这是我的代码

library(ggmap)

# Select the file from the file chooser
#fileToLoad <- file.choose(new = TRUE)

# Read in the CSV data and store it in a variable 
register_google(key = "xxxxxxx")
origAddress <- read.csv("test.csv", stringsAsFactors = FALSE)

# Loop through the addresses to get the latitude and longitude of each address and add it to the
# origAddress data frame in new columns lat and lon
for(i in 1:nrow(origAddress)) {
  result <- tryCatch(geocode(origAddress$addresses[i], output = "latlona", source = "google"),
                     warning = function(w) data.frame(lon = NA, lat = NA, address = NA))
  origAddress$lon[i] <- as.numeric(result[1])
  origAddress$lat[i] <- as.numeric(result[2])
  origAddress$geoAddress[i] <- as.character(result[3]

  )
}
# Write a CSV file containing origAddress to the working directory
write.csv(origAddress, "geocoded.csv", row.names=FALSE)

【问题讨论】:

  • 请提供一个可重现的例子。
  • 我已经编辑了原始问题

标签: r google-geocoder


【解决方案1】:

我终于让代码工作了。

library(ggmap)

# Select the file from the file chooser
#fileToLoad <- file.choose(new = TRUE)

# Read in the CSV data and store it in a variable 
register_google(key = "xxxxxxx")
origAddress <- read.csv("test.csv", stringsAsFactors = FALSE)

# Loop through the addresses to get the latitude and longitude of each address and add it to the
# origAddress data frame in new columns lat and lon
for(i in 1:nrow(origAddress)) {
  result <- tryCatch(geocode(origAddress$addresses[i], output = "latlona", source = "google", inject = paste ("components = country =" , origAddress$country[i])),
                     warning = function(w) data.frame(lon = NA, lat = NA, address = NA))
  origAddress$lon[i]`enter code here` <- as.numeric(result[1])
  origAddress$lat[i] <- as.numeric(result[2])
  origAddress$geoAddress[i] <- as.character(result[3]

  )
}
# Write a CSV file containing origAddress to the working directory
write.csv(origAddress, "geocoded.csv", row.names=FALSE)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    • 2013-02-04
    相关资源
    最近更新 更多