Posted By

dbug13 on 01/27/09


Tagged

google ruby geo geocode geocoding


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

rickfu
webstic
gutzofter
Priestd09


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


 / Published in: Ruby
 

  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
Posted By: gutzofter on September 18, 2009

what is the license this code snippet is under?

You need to login to post a comment.