Skip to content

Instantly share code, notes, and snippets.

@dkincaid
Created November 14, 2011 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dkincaid/1365208 to your computer and use it in GitHub Desktop.
Save dkincaid/1365208 to your computer and use it in GitHub Desktop.
Geocode function for R using Infochimps
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment