使用 Google API,您并不总是保证每个查询的结果“数量”相同,这就是您所描述的问题。
您需要提取的是该types : country
字段,但要执行此操作,您需要知道该国家/地区字段存在于列表中的哪个“级别”(如果存在)。
对于这个例子,我将使用我的googleway
包进行地理编码,因为它为你处理 API 查询的构建
library(googleway)
## you need a valid Google API key to use their API
api_key <- "your_api_key"
query1 <- google_geocode(address = "560065", key = api_key)
query2 <- google_geocode(address = "560066", key = api_key)
## the 'country' is in the 'address_components : types' field
# query1$results$address_components
## use an 'lapply' to find the depth of the country field
l <- lapply(query2$results$address_components[[1]]$types, function(x){
'country' %in% x
})
## so now we know how far into the list we have to go
which(l == T)
# [1] 4
query2$results$address_components[[1]]$long_name[[which(l == T)]]
# [1] "India"
所以把它包装在一个函数中:
getCountry <- function(g){
l <- lapply(g[['results']][['address_components']][[1]][['types']], function(x){
'country' %in% x
})
return(g[['results']][['address_components']][[1]][['long_name']][[which(l == T)]])
}
getCountry(query1)
# [1] "India"
getCountry(query2)
# [1] "India"
要将其合并到您的功能中,您可以这样做
getCoordinates <- function(address) {
url <- paste("http://maps.googleapis.com/maps/api/geocode/json?address=",address,"&sensor=false",sep="")
map_data <- fromJSON(paste(readLines(url),collapse=""))
l <- lapply(map_data$results[[1]]$address_components, function(x){
'country' %in% x[['types']]
})
coord <- c(map_data$results[[1]]$geometry$location$lat,map_data$results[[1]]$geometry$location$lng,
toupper(map_data$results[[1]]$address_components[[which(l == T)]]$long_name))
return(coord)
}
getCoordinates(560065)
[1] "12.9698066" "77.7499632" "INDIA"
getCoordinates(560066)
[1] "13.0935798" "77.5778529" "INDIA"