问题描述
我有一个街道地址列表,我想对县进行地理编码。我在 R 中工作。以下是简化示例。遗憾的是,由于新的 Google Api 服务条款,您需要拥有自己的 API 密钥才能运行我的代码——它不应被共享,因此请不要将其包含在您的解决方案代码中。
我怀疑这是格式问题,但我对 R 太陌生,不知道解决方案。
library(tidyverse)
library(ggmap)
register_google(key = <YOUR GOOGLE KEY>)
ltr <- letters %>% head(5)
adr <- c('110 State St,Albany,NY','100 State Cir,Annapolis,MD','206 Washington St SW,Atlanta,GA','210 State St,Augusta,ME','1100 Congress Ave,Austin,TX')
rawAdr <- data.frame(ltr,adr)
# the following only retrieves latitude and longitude
latlonAdr <- geocode(location = rawAdr$adr) %>%
bind_cols(rawAdr,.)
# the following retrieves county (among much other information),# but it is formatted in a way that is
# impossible to use. For instance,county a is in variable long_name...17,# but the same name is repeated for all addresses. The county for address b is given in
# long_name...64,again the same name for all addresses.
geoAdr <- geocode(location = rawAdr$adr,output = 'all') %>%
bind_cols(rawAdr,. )
我想要一个列出 ltr、adr 和(正确的)县的文件。感谢您的任何帮助! (抱歉,我将无法在几个小时内查看答案。)
解决方法
geocode 函数的返回值是一个长嵌套列表,您需要遍历列表以找到感兴趣的字段。
这是绕过ggmap包并返回JSON响应的解决方案,这稍微更容易解析:
library(magrittr)
ltr <- letters %>% head(5)
adr <- c('110 State St,Albany,NY','100 State Cir,Annapolis,MD','206 Washington St SW,Atlanta,GA','210 State St,Augusta,ME','1100 Congress Ave,Austin,TX')
rawAdr <- data.frame(ltr,adr)
#replace spaces with + for a valid web address
adrs <-gsub(" ","+",adr)
#add the key here to the http address
urls <-paste("https://maps.googleapis.com/maps/api/geocode/json?","address=",adrs,"&key=***keyGoesHere***",sep="")
#query the API,and search for the row that contains the word County and return that value
counties <- sapply(urls,function(url) {
print(url)
rgc <- jsonlite::fromJSON(url)
county <-rgc$results$address_components[[1]]$long_name[grep("County",rgc$results$address_components[[1]]$long_name)]
county
})
rawAdr$County <- counties
rawAdr