Created
November 14, 2011 21:17
-
-
Save dkincaid/1365208 to your computer and use it in GitHub Desktop.
Geocode function for R using Infochimps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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