Created
September 19, 2012 22:50
-
-
Save codearmorygists/3752857 to your computer and use it in GitHub Desktop.
Find City and State from Zipcode
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
require 'net/http' | |
require 'uri' | |
require "rexml/document" | |
# Retrieves US Location data based on a passed in Zipcode. Uses | |
# Google Maps geocoding service to retrieve a Hash of city, state, and zip | |
# For more info on the service see: <a href="http://code.google.com/apis/maps/documentation/geocoding/" >http://code.google.com/apis/maps/documentation/geocoding/</a> | |
# | |
# example: | |
# puts get_location_data(97030).inspect | |
# outputs: | |
# {:state=>"OR", :zip=>"97030", :city=>"Gresham"} | |
def get_location_data(zip) | |
url = "http://maps.google.com/maps/geo" | |
uri = URI.parse(url) | |
req = Net::HTTP::Get.new(uri.path + "?output=xml&q=#{zip}") | |
res = Net::HTTP.start(uri.host, uri.port) do |http| | |
http.request(req) | |
end | |
data = res.body | |
result = {} | |
address = "" | |
doc = REXML::Document.new data | |
doc.elements.each('//Placemark[1]/address') do |element| | |
address = element.text | |
end | |
if address | |
parts = address.split(/[,s*]/) | |
result[:city] = parts[0] | |
result[:state] = parts[2] | |
result[:zip] = parts[3] | |
end | |
result | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment