Retrieve City, State, and Zip info from Google Geocoding service, by passing in a Zipcode


/ Published in: Ruby
Save to your folder(s)



Copy this code and paste it in your HTML
  1. require 'net/http'
  2. require 'uri'
  3. require "rexml/document"
  4.  
  5. # Retrieves US Location data based on a passed in Zipcode. Uses
  6. # Google Maps geocoding service to retrieve a Hash of city, state, and zip
  7. # For more info on the service see: http://code.google.com/apis/maps/documentation/geocoding/
  8. #
  9. # example:
  10. # puts get_location_data(97030).inspect
  11. # outputs:
  12. # {:state=>"OR", :zip=>"97030", :city=>"Gresham"}
  13.  
  14. def get_location_data(zip)
  15. url = "http://maps.google.com/maps/geo"
  16. uri = URI.parse(url)
  17.  
  18. req = Net::HTTP::Get.new(uri.path + "?output=xml&q=#{zip}")
  19. res = Net::HTTP.start(uri.host, uri.port) do |http|
  20. http.request(req)
  21. end
  22.  
  23. data = res.body
  24. result = {}
  25. address = ""
  26.  
  27. doc = REXML::Document.new data
  28.  
  29. doc.elements.each('//Placemark[1]/address') do |element|
  30. address = element.text
  31. end
  32.  
  33. if address
  34. parts = address.split(/[,\s*]/)
  35. result[:city] = parts[0]
  36. result[:state] = parts[2]
  37. result[:zip] = parts[3]
  38. end
  39.  
  40. result
  41. end

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.