Reputation: 11657
I'm trying to reverse geocode a dataframe of lat/long coordinates. For some reason, the code spits out a single FIPS code, and stops with error messages. I'm not sure what is going on -- could it be the server rate-limiting queries?
dput(latlon)
structure(list(lat = c(38.6536995, 28.5959782, 39.2349128, 40.6988037,
36.7276906, 35.0481824), lon = c(-121.3526261, -81.4514073, -76.6117247,
-73.9183688, -119.803458, -106.4910219)), .Names = c("lat", "lon"
), row.names = c(NA, -6L), class = "data.frame")
#Reverse-Geocoding Function to get county
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)
return(as.character(json$County['FIPS']))
}
latlong2fips(latlon$lat, latlon$lon)
[1] "06067"
Warning messages:
1: In if (is.na(encoding)) return(0L) :
the condition has length > 1 and only the first element will be used
2: In if (is.na(i)) { :
the condition has length > 1 and only the first element will be used
Upvotes: 1
Views: 88
Reputation: 26248
The error is because fromJSON
doesn't accept a vector. So you need to apply fromJSON
to each element of your vector.
I also use jsonlite
as my go-to JSON parser in R.
latitude <- latlon$lat
longitude <- latlon$lon
url <- "http://data.fcc.gov/api/block/find?format=json&latitude=%f&longitude=%f"
url <- sprintf(url, latitude, longitude)
json <- RCurl::getURL(url)
## up to here gives you a vector of results, so you now need to extract the 'FIPS' for each vector element
lapply(json, function(x){
jsonlite::fromJSON(x)$County$FIPS
})
$`http://data.fcc.gov/api/block/find?format=json&latitude=38.653700&longitude=-121.352626`
[1] "06067"
$`http://data.fcc.gov/api/block/find?format=json&latitude=28.595978&longitude=-81.451407`
[1] "12095"
$`http://data.fcc.gov/api/block/find?format=json&latitude=39.234913&longitude=-76.611725`
[1] "24510"
$`http://data.fcc.gov/api/block/find?format=json&latitude=40.698804&longitude=-73.918369`
[1] "36047"
$`http://data.fcc.gov/api/block/find?format=json&latitude=36.727691&longitude=-119.803458`
[1] "06019"
$`http://data.fcc.gov/api/block/find?format=json&latitude=35.048182&longitude=-106.491022`
[1] "35001"
Upvotes: 3