简体   繁体   中英

Geocode in R with Bing

I would like to use the Bing API to batch geocode. I found a package on github at https://github.com/gsk3/taRifx.geo/blob/master/R/Contributed.R however, I cannot seem to figure out how to use its function on a vector. When I try the following everything works just fine:

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

But if I replaced the location with a vector of locations, only a single coordinate pair is returned and the following warning is returned:

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

I also tried the following alternative function but again only a single pair of coordinates is returned. With ggmap's geocode I'm able to run this process on a vector but it's API is limited to 2500 queries/day so I'm stuck trying to use Bing (Yahoo api is too difficult to obtain).

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")

Any help is much appreciated.

Without having used the package in question, it looks like the geocode function isn't vectorised. A quick fix is to make it vectorised:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM