Skip to content

Instantly share code, notes, and snippets.

@rahuljiresal
Created February 11, 2014 17: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 rahuljiresal/8939442 to your computer and use it in GitHub Desktop.
Save rahuljiresal/8939442 to your computer and use it in GitHub Desktop.
Reverse Geocode Coordinates to City
# get the geocoder gem by doing 'gem install geocoder' or adding 'gem geocoder' to your Gemfile
require 'geocoder'
# configure geocoder service -- I'm using bing because it gives more API calls per day
Geocoder.configure(
# geocoding service (see below for supported options):
:lookup => :bing,
# IP address geocoding service (see below for supported options):
:ip_lookup => :maxmind,
# to use an API key:
:api_key => "YOUR_API_KEY",
# geocoding service request timeout, in seconds (default 3):
:timeout => 10,
# set default units to kilometers:
:units => :km,
)
# get all the location co-ordinates
locations = LocationData.all
# create a new array to store all the cities you get from reverse geocoding
cities = Array.new
locations.each do |location|
# create the query string in the format "49.277826,-123.125227"
query = location.latitude.to_s + "," + location.longitude.to_s
# Geocoder returns an array, just take the first object
result = Geocoder.search(query).first
# check for null, get the city, and put it in the array
if (result)
city = result.city
cities.push(city)
end
end
# count the number for each city
counts = Hash.new(0)
cities.each { |c| counts[c] += 1 }
counts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment