How to Get FIPS Codes from Latitude and Longitude

FIPS codes are unique identifiers for geographic units within the US. Although they have technically been withdrawn as a standard, they are still widely used in political science and other applications for geographic categorization of data. For example, the CBS/New York Times monthly polling series includes the FIPS code for the county in which each respondent lives.

Say you have some other data with latitude and longitude indicators that you would like to combine with FIPS-coded data. I have written a short Ruby script below that will do exactly this. It assumes that you have your data in .csv format, since that is a pretty generic format and you can usually convert your data to that if it is currently stored in another form. You will also need the Ruby geokit gem:

gem install geokit

Once you have the data ready and the gem installed, you are good to go. Just fill out the lines with comments and run the following from IRB (or however you like to run your Ruby scripts):

require 'geokit'
require 'CSV'

filename = # csv file
fipslist = []

CSV.foreach(filename) do |row|
  lat = # latitude column
  long = # longitude column
  ll = GeoKit::LatLng.new(lat, long)
  fcc = Geokit::Geocoders::FCCGeocoder.reverse_geocode(ll)
  puts fcc.district_fips
  fipslist << fcc.district_fips
end

You can then do anything you want to with theĀ fipslist object, including writing it out to a file. If you want to share improvements or have questions, please use the comments section below.