Created
May 6, 2014 03:35
-
-
Save ramhiser/f09a71d96a4dec80994c to your computer and use it in GitHub Desktop.
Latitude/Longitude to FIPS Codes via the FCC's API
This file contains hidden or 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
# FCC's Census Block Conversions API | |
# http://www.fcc.gov/developers/census-block-conversions-api | |
latlong2fips <- function(latitude, longitude) { | |
url <- "http://data.fcc.gov/api/block/find?format=json&latitude=%f&longitude=%f" | |
url <- sprintf(url, latitude, longitude) | |
json <- RCurl::getURL(url) | |
json <- RJSONIO::fromJSON(json) | |
as.character(json$County['FIPS']) | |
} | |
# Orange County | |
latlong2fips(latitude=28.35975, longitude=-81.421988) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this useful code! Came in very clutch for me.
Here's my edit:
Use Lat/Long to lookup missing county FIPS ------------------------------
if (!require("RJSONIO")) install.packages("RJSONIO")
latlong2fips =
function(latitude, longitude) {
url <- "https://geo.fcc.gov/api/census/area?lat=%s&lon=%s&censusYear=2010&format=json"
url <- sprintf(url, latitude, longitude)
json <- RJSONIO::fromJSON(url)
as.character(json[["results"]][[1]][["county_fips"]])
}
latlong2fips(latitude=28.35975, longitude=-81.421988)
The result:
"12095"
Since it's probably most useful to use this not for a single lookup, but for lots of inputs, here's a short code snippet to help with that (if you have a vectorized way of doing it, please share!)
Make a data.table
a = data.table(latitude=c(28.35975,28.36975,29.33), longitude=c(-81.421988,-81.431988,-81.55))
Pre-allocate space
a[,fips:="0"]
Loop and add the new FIPS codes
for(i in 1:nrow(a)){
lat = a[i, latitude]
lon = a[i, longitude]
a[i, fips := latlong2fips(latitude = lat, longitude = lon)]
}