public
Created

Geocode function for R using Infochimps

  • Download Gist
getcode.R
R
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
geocode = function(location) {
library(RJSONIO)
api.uri = "http://api.infochimps.com/"
geocode.uri = "geo/utils/geolocate?"
api.key = "apikey=xxxxxxxxxxxx"
 
print(location)
uri = paste(api.uri, geocode.uri, api.key, "&f.address_text=", location, sep="")
raw.data = readLines(uri, warn="F")
results = fromJSON(raw.data)
if (!is.null(results[[2]][[1]]["county_id"])) {
county = results[[2]][[1]][["county_id"]]
df = data.frame(county=county)
}
if (!is.null(results[[2]][[1]][["coordinates"]])) {
long = results[[2]][[1]][["coordinates"]][[1]]
lat = results[[2]][[1]][["coordinates"]][[2]]
if (is.null(df)) {
df = data.frame(lat=as.numeric(lat), long=as.numeric(long))
}
else {
df = cbind(df,data.frame(lat=as.numeric(lat), long=as.numeric(long)))
}
}
df
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.