R Geocode с Google с поисковыми ограничениями на страну - PullRequest
0 голосов
/ 11 февраля 2020

Я пытаюсь отфильтровать результаты поиска только из определенной страны, поскольку иногда 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)

1 Ответ

0 голосов
/ 27 февраля 2020

Я наконец-то получил работающий код.

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)
...