谷歌api返回错误的价值观

时间:2016-12-08 05:37:28

标签: r google-maps-api-3 rjson

你可以帮我从谷歌API中提取信息,当我提供地址变量:560066,560065(bengaluru city的密码)时,address_components有不同的长度(在这种情况下为4和5)

这可能会返回错误的数据。让我说我想要国家信息,以下将返回INDIA的前和错误:超出界限'对于后者

是否存在通用方式,以便为两种情况返回国家/地区值

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)

1 个答案:

答案 0 :(得分:2)

使用Google API,您并不总是保证使用相同的号码&#39;每个查询的结果,这是您正在描述的问题。

您需要提取的内容是types : country字段,但为了做到这一点,您需要知道什么是&#39;级别&#39;在列表中,国家/地区字段存在(如果存在)。

对于此示例,我将使用我的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"