2

当我提供地址变量:560066、560065(班加罗尔市的密码)时,您能帮我从谷歌 API 中提取信息吗,地址组件有不同的长度(在这种情况下为 4 和 5)

这可能会返回错误的数据。假设我想要国家信息,以下将返回印度为前者,后者返回“错误:越界”

是否有一种通用方法可以为两种情况返回国家/地区价值

library(rjson) # load rjson package

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=""))
coord <- c(map_data$results[[1]]$geometry$location$lat,map_data$results[[1]]$geometry$location$lng, toupper(map_data$results[[1]]$address_components[[5]]$long_name))
return(coord)
}

g <- getCoordinates(560066)
4

1 回答 1

2

使用 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"
于 2016-12-08T07:20:52.710 回答