使用 Bing 在 R 中进行地理编码

Geocode in R with Bing

我想使用 Bing API 来批量地理编码。我在 https://github.com/gsk3/taRifx.geo/blob/master/R/Contributed.R 的 github 上找到了一个包,但是,我似乎无法弄清楚如何在矢量上使用它的功能。当我尝试以下操作时,一切正常:

devtools::install_github("gsk3/taRifx.geo")
options(BingMapsKey='my_APIKEY')
geocode("New York,NY", service="bing", returntype="coordinates")

但是如果我用位置向量替换位置,则只会返回一个坐标对并返回以下警告:

Warning message: In if (is.na(x) | gsub(" *", "", x) == "") return(c(NA, NA)) : the condition has length > 1 and only the first element will be used

我还尝试了以下替代函数,但同样只返回一对坐标。使用 ggmap 的 geocode 我可以 运行 向量上的这个过程但是它 API 被限制为 2500 queries/day 所以我一直在尝试使用 Bing(雅虎api太难获取了)

bGeoCode <- function(str, BingMapsKey){
    require(RCurl)
    require(RJSONIO)
    u <- URLencode(paste0("http://dev.virtualearth.net/REST/v1/Locations?q=", str, "&maxResults=1&key=", BingMapsKey))
    d <- getURL(u)
    j <- fromJSON(d,simplify = FALSE) 
    if (j$resourceSets[[1]]$estimatedTotal > 0) {
      lat <- j$resourceSets[[1]]$resources[[1]]$point$coordinates[[1]]
      lng <- j$resourceSets[[1]]$resources[[1]]$point$coordinates[[2]]
    }
    else {    
      lat <- lng <- NA
    }
    c(lat,lng)
}  

bGeoCode(data$location, "my_APIKEY")

非常感谢任何帮助。

在没有使用相关包的情况下,geocode 函数似乎未被矢量化。一个快速的解决方法是将其矢量化:

geocodeVect <- Vectorize(geocode, vectorize.args="x")
geocodeVect(multiple_locations, ...)